So I have this code
int results[] = new int[13];
results[0]=19;
results[1]=22;
results[2]=21;
results[3]=25;
results[4]=32;
results[5]=38;
results[6]=16;
results[7]=31;
results[8]=30;
results[9]=26;
results[10]=19;
results[11]=17;
results[12]=23;
for(int i=0;i<results.length;i++)
System.out.println(results[lenght,Integer.MIN_VALUE,Integer.MAX_VALUE]);
}
}
How do I print the lenght of the array, the min value and the max malue all in a same array?
List<Integer>results2=new ArrayList<>();
for (int result : results) {
results2.add(result);
}
System.out.println("Minimum: " + Collections.min(results2));
System.out.println("Maximum: " + Collections.max(results2));
System.out.println("Amount of elements: " + results2.size());
Related
String[][] array = {{"Checkup", "60"},
{"Repairing tooth", "150"},
{"Cleaning", "30"}}; // Menu of treatments
String[] array2 = new String [10]; // New array that saves up to 10 elements(treatments)
int cost = 0;
int treatment = 0;
Scanner input = new Scanner(System.in);
System.out.println("Control" + " " + "1");
System.out.println("Repair tooth:" + " " + "2");
System.out.println("Cleaning:" + " " + "3");
int n = array.length;
for (int i=0; i<n; i++) {
for (int j=0; i<n ; j++) {
System.out.println();
treatment = input.nextInt();
if (treatment==1) {
cost += Integer.parseInt(array[i][1]);
System.out.print("Total cost so far: " + cost);
}
if (treatment==2) {
cost += Integer.parseInt(array[i+1][1]);
System.out.print("Total cost so far: " + cost);
}
if (treatment==3) {
cost += Integer.parseInt(array[i+2][1]);
System.out.print("Total cost so far: " + cost);
}
}
}
How do I move on from here? I figured that I have to store the input in the new array and exit the loop after 10 treatments or add an option to the user to print out the receipt when they're done.
The receipt needs to print all the chosen treatments along with the cost for each individual treatment. I will also need to add a variable to add a total amount for all the chosen treatments.
Here it is what you are trying to do, As the treatments are fixed so you can just index them as 0, 1, 2. One thing you can do is to make a hashmap in which you can store the treatment name and its cost (String,int) every time the user wants to enter.
Look at the code below
import java.util.*;
import java.util.HashMap;
public class treatment {
public static void main(String []args) {
String[][] array = {{"Checkup", "60"},
{"Repairing tooth", "150"},
{"Cleaning", "30"}}; // Menu of treatments
// New array that saves up to 10 elements(treatments)
HashMap<String, Integer> treat = new HashMap<String, Integer>();
int cost = 0;
int treatment = 0;
Scanner input = new Scanner(System.in);
int n = array.length;
int i =0;
char c = '\0';
do {
System.out.println("\n\nControl" + " " + "1");
System.out.println("Repair tooth:" + " " + "2");
System.out.println("Cleaning:" + " " + "3");
System.out.println("Exit: " + "-1");
System.out.println();
System.out.print("Enter treatment value (1, 2, 3): ");
treatment = input.nextInt();
if (treatment==1){
i = 0;
cost += Integer.parseInt(array[0][1]);
System.out.println("\nTotal cost so far: " + cost);
}
else if (treatment==2) {
i = 1;
cost += Integer.parseInt(array[1][1]);
System.out.println("\nTotal cost so far: " + cost);
}
else if (treatment==3) {
i = 2;
cost += Integer.parseInt(array[2][1]);
System.out.println("\nTotal cost so far: " + cost);
}
treat.put(array[i][0], cost);
} while (treatment != -1);
System.out.println("Total COst is : " + cost);
System.out.println("The treatements you opt for are:\n");
System.out.println(treat);
System.out.println("\n");
}
}
I set up this benchmark test
static Random rand = new Random();
static int n = rand.nextInt(999) + 1;
#Setup
public static final void setup(){
int x = 1000;
for (int i = 0; i < x; i++){
id.add(rand.nextInt(500) + 1);
property_address.add(rand.nextInt(1000) + 1);
email.add(rand.nextInt(1000) + 1);
owner_address.add(rand.nextInt(1000) + 1);
price.add(rand.nextInt(1000) + 1);
date_sold.add(rand.nextInt(1000) + 1);
}
System.out.println("Setup Complete");
}
#Benchmark
public static void getPropertybyId(){
System.out.println(id.get(n) +", "+ property_address.get(n) +", "+
first_name.get(n) +", "+ last_name.get(n) +", "+
email.get(n) +", "+
owner_address.get(n) +", "+
price.get(n)+", "+
date_sold.get(n));
}
Because I want to see how fast getPropertyById works, I want to populate the Lists id/property/email with 1000 random integer elements and then get a random element from each array at the same index (n).
This is the actual method but I took out the scanner in order to use random data so the benchmarking doesn't have to wait for user input
public static void getPropertybyId(){
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Enter an id number to search properties: ");
int n = reader.nextInt(); // Scans the next token of the input as an int.
reader.close();
System.out.println(id.get(n) +", "+ property_address.get(n) +", "+ first_name.get(n) +", "+ last_name.get(n) +", "+
email.get(n) +", "+
owner_address.get(n) +", "+
price.get(n)+", "+
date_sold.get(n));
}
I get the following error
java.lang.IndexOutOfBoundsException: Index: 902, Size: 0
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at org.sample.MyBenchmark.getPropertybyId(MyBenchmark.java:80)
public static void main(String []args){
Random gen = new Random();
int[] numbers = new int[6];
int sum, product;
for (int i = 1; i < numbers.length; i++){
int pick = gen.nextInt(10);
numbers[i] = pick;
sum = (numbers[1]+numbers[2]+numbers[3]+numbers[4]+numbers[5]);
product = sum *2;
System.out.println("Random number: " + numbers[i]);
System.out.println("Product is: " + product);
}
}
It prints this:
Random number: 0
Product is: 0
Random numbers: 8
Product is: 16
Random number is: 9
Product is: 34
Random number is: 3
Product is 40
Random number is: 9
Product is 58
Which is fine, but I only want the total number, being 58. Something Simple :/ I'm new at this.
When ever you iterate through the loop you're invoking the System.out.println method, that's why you're getting all the output, you need to take the methods out of your for loop
Delete these:
System.out.println("Random number: " + numbers[i]);
System.out.println("Product is: " + product);
Put this one outside the for loop:
System.out.println("Product is: " + product);
Remove the following statements from the loop:
System.out.println("Random number: " + numbers[i]);
System.out.println("Product is: " + product);
And add the following outside the loop:
System.out.println("Product is: " + product);
Get this System.out.println("Product is: " + product); out of your loop
I am trying to store the data that's created in the while loop in the list variable so that I can use it later with the JOptionPane.INFORMATION_MESSAGE.
I tried using an array to store the data but it would not work.
Please let me know what I am missing.
package loops;
import java.text.DecimalFormat;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class Statistics
{
public static void main(String[] args)
{
int observations = 1,
num = 0,
sum = 0,
max = Integer.MIN_VALUE,
min = Integer.MAX_VALUE;
double mean = 0.0;
String userEntry = "",
result,
list = " ",
seperator = "\n***********\nYou entered the following observations: ";
DecimalFormat twoDigits = new DecimalFormat ("0.00");
userEntry = JOptionPane.showInputDialog ("Enter observation # " + observations +
" (or \"end\" to quit) ");
//num = Integer.parseInt(userEntry);
String[] list2 = new String[num];
while(!userEntry.equalsIgnoreCase("end"))
{
num = Integer.parseInt(userEntry);
observations ++;
userEntry = JOptionPane.showInputDialog ("Enter observation #" + observations +
" (or \"end\" to quit) ");
//num = Integer.parseInt(userEntry);
//num = Integer.parseInt(userEntry);
//list = "\n" + num;
//list = list.toString();
sum += num;
if(num > max)
{
max = num;
}
if(num < min)
{
min = num;
}
//Integer.toString(num);
//ArrayList<String> list = new ArrayList<String>();
//list.add(num);
//list = "\n" + Integer.toString(num);
//String[] list2 = new String[num];
//for(String list1 : list2)
//{
list = "\n" + num;
//}
}
observations --;
mean = sum / (double)observations;
//twoDigits.format(mean);
if(observations == 0)
{
result = "no observations selected";
}
else
{
result = "You entered " + observations +
(observations == 1 ? " observation" : " observations");
result = result + "\nThe minimum is " + min;
result = result + "\nThe maximum is " + max;
result = result + "\nThe sum is " + sum;
result = result + "\nThe mean is " + twoDigits.format(mean);
result = result + seperator;
result = result + list;
}
JOptionPane.showMessageDialog(null, result,
"Results", JOptionPane.INFORMATION_MESSAGE);
//observations --;
System.exit(0);
}
}
Try using ArrayList instead of []. Example based on your code is shown below.
package loops;
import java.text.DecimalFormat;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class Statistics {
public static void main(String[] args) {
// method local variables
int observations = 0;
int num = 0;
int sum = 0;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
double mean = 0.0;
String userEntry = "";
String result;
String list = " ";
String seperator = "\n***********\nYou entered the following observations: ";
DecimalFormat twoDigits = new DecimalFormat("0.00");
ArrayList<Integer> intList = new ArrayList<Integer>();
// get user entry from JOptionPane
userEntry = JOptionPane.showInputDialog("Enter observation # " + observations + " (or \"end\" to quit) ");
// iterate until user enters end
while (userEntry.equalsIgnoreCase("end") == false) {
observations++;
num = Integer.parseInt(userEntry);
userEntry = JOptionPane.showInputDialog("Enter observation #" + observations + " (or \"end\" to quit) ");
sum = sum + num;
// change number to max if > max
if (num > max) {
max = num;
}
// change number to min if < min
if (num < min) {
min = num;
}
// add the number to the string and to the list
list = list + "\n" + num;
intList.add(num);
}
echoList(intList);
mean = sum / (double) observations;
if (observations == 0) {
result = "no observations selected";
}
else {
result = "You entered " + observations + (observations == 1 ? " observation" : " observations");
result = result + "\nThe minimum is " + min;
result = result + "\nThe maximum is " + max;
result = result + "\nThe sum is " + sum;
result = result + "\nThe mean is " + twoDigits.format(mean);
result = result + seperator;
result = result + list;
}
// show results and exit
JOptionPane.showMessageDialog(null, result, "Results", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
private static void echoList(ArrayList<Integer> intList) {
System.out.println("------------------------------");
System.out.println("Got " + intList.size() + " integers.");
for(Integer i : intList) {
System.out.println("\t" + i);
}
System.out.println("------------------------------");
}
}
JOptionPane.showInputDialog() will return the string the user has entered if the user hits ok, and returns null otherwise.
Therefore, if the user hits cancel, your while condition (userEntry.equalsIgnoreCase("end") == false) will throw a NullPointerException.
Therefore, it's safer to change the while condition to (userEntry != null).
Now, if you want to store all the user entries, use a list of integers, say List<Integer> userEntries
List<Integer> userEntries = new ArrayList<>();
while (userEntry.equalsIgnoreCase("end") == false)
{
observations++;
num = Integer.parseInt(userEntry);
userEntries.add(num);
...
}
This question already has answers here:
Comparing two integer arrays in Java
(10 answers)
Closed 7 years ago.
The statement before the begining of while loop System.out.println("Value of i before loop = " + i); is not being printed and the value of i in the loop is not being printed starting from 1. Instead it starts printing from a random big int.
package main;
import java.util.Random;
public class Main {
public static void main(String args[]){
Random ran = new Random();
int[] in = {2,5,9};
int[] c_gen = new int[3];
int i = 0;
System.out.println("Value of i before loop = " + i);
while(!(c_gen.equals(in))){
c_gen[0] = ran.nextInt(10);
c_gen[1] = ran.nextInt(10);
c_gen[2] = ran.nextInt(10);
i++;
System.out.println(c_gen[0] + " " + c_gen[1] + " " + c_gen[2] + " .................." + i);
}
System.out.print("in = ");
for(int x : in)
System.out.print(x + " ");
System.out.print("\n" + "c_gen = ");
for(int x : c_gen)
System.out.print(x + " ");
System.out.println("\n" + "i = " + i);
}
}
You are directly comparing arrays resulting in an infinite loop. Those results are being printed but are going to be at the top of tons and tons of output. Fix your comparison.
Sotirios' intuition is correct - your bug is in the line while(!(c_gen.equals(in))). You can't compare arrays for equality using the .equals(...) method because "arrays inherit their equals-method from Object, [thus] an identity comparison will be performed for the inner arrays, which will fail, since a and b do not refer to the same arrays." (source). Thus because c_gen and in will always refer to different arrays (even if their contents are the same), your loop will go forever.
Try Arrays.equals(..) instead:
public static void main(String[] args) {
Random ran = new Random();
int[] in = {2,5,9};
int[] c_gen = new int[3];
int i = 0;
System.out.println("Value of i before loop = " + i);
while(!Arrays.equals(in, c_gen)){
c_gen[0] = ran.nextInt(10);
c_gen[1] = ran.nextInt(10);
c_gen[2] = ran.nextInt(10);
i++;
System.out.println(c_gen[0] + " " + c_gen[1] + " " + c_gen[2] + " .................." + i);
}
System.out.print("in = ");
for(int x : in)
System.out.print(x + " ");
System.out.print("\n" + "c_gen = ");
for(int x : c_gen)
System.out.print(x + " ");
System.out.println("\n" + "i = " + i);
}
This works (terminates in finite time) for me, with sample output:
Value of i before loop = 0
1 9 9 ..................1
5 4 1 ..................2
1 1 6 ..................3
1 3 6 ..................4
.... //Omitted because of space
6 5 8 ..................1028
2 5 9 ..................1029
in = 2 5 9
c_gen = 2 5 9
i = 1029
I get:
Value of i before loop = 0
2 2 1 ..................1
2 2 4 ..................2
...
Suggest you rebuild the project and try again.
As originally posted your code will not terminate because int[].equals(int[]) will not do what you expect.
You could try this though.
private static boolean equals(int[] a, int[] b) {
if (a == null && b == null) {
// Both null
return true;
}
if (a == null || b == null) {
// One null
return false;
}
if (a.length != b.length) {
// Differ in length.
return false;
}
for (int i = 0; i < a.length; i++) {
if (a[i] != b[i]) {
// Mismatch
return false;
}
}
// Same.
return true;
}
public void test() {
Random ran = new Random();
int[] in = {2, 5, 9};
int[] c_gen = new int[3];
int i = 0;
System.out.println("Value of i before loop = " + i);
while (!equals(c_gen, in)) {
c_gen[0] = ran.nextInt(10);
c_gen[1] = ran.nextInt(10);
c_gen[2] = ran.nextInt(10);
i++;
System.out.println(c_gen[0] + " " + c_gen[1] + " " + c_gen[2] + " .................." + i);
}
System.out.print("in = ");
for (int x : in) {
System.out.print(x + " ");
}
System.out.print("\n" + "c_gen = ");
for (int x : c_gen) {
System.out.print(x + " ");
}
System.out.println("\n" + "i = " + i);
}