I'm having a problem of storing multiple input value in Java. First, I'm using an ArrayList to store how many inputs the user has entered. Then I want to do the calculation after collect all the input.
My program allows user to enter 5 different values between 1 to 5. 1 is equal to 100, 2 is equal to 200, 3 is equal to 300, 4 is equal to 400, 5 is equal to 500
I create an Array to store these values
double numberArray[] = {100, 200, 300, 400, 500};
When user enters 1, the ArrayList will store the first input value. When user enters 2, the ArrayList will store the second input value and so on. When user hit "n", it will exit and do the addition. It means it will add 100 and 200 together which the output will equal to 300.
However, the problem is when the user keeps input the number, my program will only add up the total of the first input together which is 100 + 100 even I enter 2 as the second input.
Here is my code:
import java.util.*;
public class Total{
static int total;
public static void main(String[] args) {
int numberArray[] = {100, 200, 300, 400, 500};
List<String> list = new ArrayList<String>();
Scanner input = new Scanner(System.in);
do{
System.out.println("Add item? Please enter \"y\" or \"n\"");
if (input.next().startsWith("y")){
System.out.println("Enter item number: ");
list.add(input.next());
if (list.contains("1")){
int item1 = numberArray[0];
total = total + item1;
} else if(list.contains("2")){
int item2 = numberArray[1];
total = total + item2;
} else if(list.contains("3")){
int item3 = numberArray[2];
total = total + item3;
} else if(list.contains("4")){
int item4 = numberArray[3];
total = total + item4;
} else {
System.out.println("You have entered invalid item number!");
break;
}
}else{
System.out.println("You have entered all the item(s).");
break;
}
} while(true);
System.out.println(The total is: " + total);
}
}
totalfrom staticmainmethod.totalshould be static, otherwise your code will not complieinputtwice, as MadProgrammer noted, and the way you detect which option was entered is fundamentally flawed. It's pretty simple to see where your error lies; just trace what's in the list at each step. After you put1in the list, it will always be in the list, even the second time around. How would the latter if statements ever be called in this case?