public class MetricConversion {
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
String masses = "null";
String volumes = "null";
String temps = "null";
String lengths = "null";
int answer1 = 0;
String[] options = {"Mass = 1","Temperature = 2","Length = 3","Volume = 4"};
System.out.println("What would you like to convert?");
for(int i = 0;i<options.length;i++)
System.out.println(options[i]);
while(!input.hasNextInt() || input.nextInt() > options.length)
{
String garbage = input.nextLine();
System.out.println("That input is not valid, try again");
}
answer1 = input.nextInt();
input.nextLine();
The problem I am having is that the
while(!input.hasNextInt() || input.nextInt() > options.length)
is taking 2 valid inputs instead of 1 in order to make
answer1 = input.nextInt();
For example, when entering an invalid input it correctly prints my error message, but when entering a valid input I have to enter it twice in order to break the loop. However if I use the while loop without the || it only takes one value like it's supposed to.
You're consuming the value without assigning it to a variable. You can assign it within the loop condition like this:
while(!input.hasNextInt() || (answer1 = input.nextInt()) > options.length)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments