我如何在while循环中使用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 } 

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

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

这只是一项任务而非宣言

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

删除循环内的int声明。

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

根据我的理解,您的要求是,一次又一次地提示用户,直到您匹配正确的号码。 如果是这种情况,它将如下所示:循环迭代只要用户输入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"); } 

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

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