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();
我遇到的问题是
while(!input.hasNextInt() || input.nextInt() > options.length)
正在取2个有效输入而不是1来制作
answer1 = input.nextInt();
例如,当输入无效输入时,它会正确打印我的错误消息,但是当输入有效输入时,我必须输入两次才能打破循环。但是,如果我使用没有||的while循环它只需要一个像它应该的值。
答案 0 :(得分:2)
您正在使用该值而不将其分配给变量。您可以在循环条件中分配它,如下所示:
while(!input.hasNextInt() || (answer1 = input.nextInt()) > options.length)
答案 1 :(得分:0)
您正在使用while循环中的scanner参数:
while(!input.hasNextInt()){
int argument = input.nextInt();
if(argument > options.length){
System.out.println("That input is not valid, try again");
continue; // get back to the start
}
// correctly handle your argument
}