Java扫描程序,而循环有条件地不尊重条件

时间:2016-12-11 21:01:04

标签: if-statement while-loop integer java.util.scanner

我试图解决这个问题几个小时,不明白这个问题。

代码

import java.util.Scanner;

public class Scan {

public static void main(String args[]) {

System.out.println("Enter Number");

Scanner test = new Scanner(System.in);

int g = test.nextInt();

while( g != -1 ){

System.out.println("Enter Number");

test.nextInt();  
}

test.close();

return;
} 
}

问题

(1)如果输入数字!= -1,则while循环按预期工作。

(2)如果在第一次提示时输入-1,代码将忽略while循环,关闭扫描仪并退出main方法。

(3)但是,如果你输入一个数字!= -1,然后输入-1,只要你继续输入整数,while循环就会继续。

为什么它不像(1)中那样退出while循环?

1 个答案:

答案 0 :(得分:0)

当您从用户那里获取输入时,在while loop内,它存储在哪里?我不应该test.nextInt();g = test.nextInt();吗?

您遇到此问题,因为当您从while loop内的用户处收集输入时,您不会将其存储在变量g中,这就是您while loop的原因用户输入-1时不会中断。

在解决了这个小错误之后,这里是你的代码。

import java.util.Scanner;

public class Scan {

public static void main(String args[]) {

System.out.println("Enter Number");

Scanner test = new Scanner(System.in);

int g = test.nextInt();

while( g != -1 ){

System.out.println("Enter Number");

g = test.nextInt();   //your input should be stored in g so that while loop exits if g becomes equal to -1
}

test.close();

return;
} 
}