我如何在while循环中使用java扫描程序

时间:2012-11-08 08:09:50

标签: java

这是我到目前为止所做的:

int question = sc.nextInt(); 

while (question!=1){

    System.out.println("Enter The Correct Number ! ");

    int question = sc.nextInt(); // This is wrong.I mean when user enters wrong number the program should ask user one more time again and again until user enters correct number.
    // Its error is : duplicate local variable

}

4 个答案:

答案 0 :(得分:1)

您正在尝试重新声明循环内的变量。您只想为现有变量赋予不同的值:

while (question != 1) {
    System.out.println("Enter The Correct Number ! ");
    question = sc.nextInt();
}

这只是作业而非声明

答案 1 :(得分:1)

你在循环外声明int问题,然后在循环内再次声明。

删除循环中的int声明。

在Java中,变量的范围取决于它声明的子句。如果将一个变量INSIDE声明为try或while或其他许多子句,那么该变量就是该子句的本地变量。

答案 2 :(得分:1)

根据我的理解,您的要求是一次又一次地提示用户,直到您匹配正确的号码。如果是这种情况,则如下所示:只要用户输入1,循环就会迭代。

Scanner sc = new Scanner(System.in);        
System.out.println("Enter The Correct Number!");
int question = sc.nextInt(); 

while (question != 1) {
    System.out.println("please try again!");
    question = sc.nextInt(); 
}
System.out.println("Success");

答案 3 :(得分:0)

重复使用question变量,而不是重新声明它。

int question = sc.nextInt(); 
while (question != 1) {
    System.out.println("Enter The Correct Number ! ");
    question = sc.nextInt(); // ask again
}