Java input validation in while loop

Status
You're currently viewing only Faramir's posts. Click here to go back to viewing the entire thread.
Not open for further replies.

Faramir

Ars Legatus Legionis
36,356
Subscriptor
It looks like your curly braces are screwy there. Also you aren't reassigning values. I don't know scanner because it's newish, but the code should look something like this:
Code:
public static ArrayList<Integer> readInputs() {
  ArrayList<Integer> inputs = new ArrayList();
  System.out.println("Please enter the cost of each product, enter Q to quit:");
  Scanner in = new Scanner(System.in);
  int value = 0;
  while(in.hasNextInt()) {
    value = in.nextInt();
    if(value < 1) {
      System.out.println("Values must be positive, try again");
    } else {
      inputs.add(value);
    }
  }
  return inputs;
}
 
Status
You're currently viewing only Faramir's posts. Click here to go back to viewing the entire thread.
Not open for further replies.