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 循环 它只需要一个值,就像它应该的那样。
您正在使用该值而不将其分配给变量。您可以在循环条件中分配它,如下所示:
while(!input.hasNextInt() || (answer1 = input.nextInt()) > options.length)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句