2012-11-08 70 views
1

這是我到目前爲止有:如何使用Java的掃描儀在while循環

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 

} 

回答

1

你試圖重新聲明變量的循環中。你只希望給現有變量不同的值:

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

這只是一個分配而在一個聲明

0

重新使用question變量而不是重新聲明它。

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

謝謝ü所有Fella的:)我想 – user1808537

1

你在循環內部聲明int問題,然後再次在循環內部聲明。

刪除循環內的int聲明。

在Java中,變量的作用域取決於聲明哪個子句。如果在INSIDE中聲明變量INSIDE或try或while或其他子句,則該變量對於該子句是局部的。

1

從我的低估你的要求是,一次又一次地提示用戶,直到你匹配正確的數字。如果是這樣的情況下,將如下:循環迭代aslong作爲用戶輸入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"); 
    } 
+0

感謝ü我的朋友,這是非常有幫助:) – user1808537

+0

你能如果你滿意,請打勾作爲答覆或upvote :) –