[英]how can i use java scanner in while loop
這是我到目前為止:
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 中,變量的范圍取決於它在哪個子句中聲明。如果在 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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.