Java input validation in while loop

Status
Not open for further replies.

Daniel

Ars Praefectus
3,688
Subscriptor
So I'm just starting to learn Java, I'm fumbling my way through my first program that isn't some version of Hello World. The program is actually working, there are a few other sections, but in this one section I'm having an issue trying to keep the user from entering a negative number. Well, it works, but only on the first number entered, if I enter a positive number first into the array then enter a negative number as the 2nd number it doesn't trigger the values < 1 part of the code. I figure I'm just placing it wrong in that it isn't being run each time the loop is run. I tried moving the if statement below the line with the while in it but I couldn't get that working.

edit: to clarify, I'd like to inform the user with the "values must be positive, try again" line and have them enter the value as a positive again, not just end the program.

Any suggestions?

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 values = in.nextInt();
if (values < 1)
{System.out.println("Values must be positive, try again");
}
while (in.hasNextInt())

{
inputs.add(in.nextInt());
}
return inputs;
}
 

Daniel

Ars Praefectus
3,688
Subscriptor
That's what is strange, to me anyway, when I change it to this

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 values = in.nextInt();

while (in.hasNextInt())
if (values < 1)
{System.out.println("Values must be positive, try again");
}
{
inputs.add(in.nextInt());
}
return inputs;
}

Then it doesn't check for the negative at all on the first pass, or it doesn't seem to anyway, but then when I enter the second number (which is a positive) it goes into an infinite loop scrolling the message about values must be positive, try again, until I break the program. It also seems to break the "enter q to quit" part as well.
 

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
Not open for further replies.