2014-01-18 75 views
0

該計劃旨在增加由計算機生成2張隨機數,當用戶回答出了問題,電腦會告訴用戶再次嘗試,通過使用while循環。一旦用戶輸入正確的號碼,程序將停止。我必須在while循環中計算錯誤的計數,但是,當它是第二次嘗試時,它給了我錯誤的計數1.請告訴我代碼中哪裏出錯。謝謝。如何使用while循環,以及如何使用計數在循環

import java.util.Scanner; 

public class add { 
    public static void main(String[] args) { 
     Scanner input = new Scanner(System.in); 

     int num1 = (int) (Math.random() * 10); 
     int num2 = (int) (Math.random() * 10); 
     int wrong = 0; 

     System.out.println("What is " + num1 + "+" + num2 + "=" + "?"); 
     int answer = input.nextInt(); 

     while (num1 + num2 != answer) { 
      System.out.println("Wrong answer, Try again . " + 
        "What is " + num1 + "+" + num2 + "? "); 
      answer = input.nextInt(); 
      System.out.println("The number of attemt is " + wrong); 
      ++wrong; 
     } 
     System.out.println("You got it correct !"); 
    } 
} 
+1

縮進代碼。 – tbodt

+0

'的System.out.println( 「attemt的數量是」 + ++錯);' – MariuszS

+0

交換下面陳述 的System.out.println( 「attemt的數量是」 +錯); ++錯誤; –

回答

0

只要改變

wrong = 0 

wrong = 1 

錯誤可能應該重命名爲numberOfAttempts。

0

初始化wrong 1而不是0

int wrong = 1; 

的變量一個更合適的名稱將是attempt如果採取這種做法。

+0

我初始化int錯誤= 1;然而;當我輸入錯誤的答案時,我沒有得到輸出「嘗試次數爲1」 – user3196297

+0

@ user3196297這是因爲只有在閱讀新答案後纔打印該輸出。 – Henry

2

的錯誤是在增加用戶已經得到了錯誤後打印數量 「你有X錯誤」

1

只要把++wrong上述System.out.println("The number of attemt is " + wrong);

while (num1 + num2 != answer) { 
      System.out.println("Wrong answer, Try again . " + 
        "What is " + num1 + "+" + num2 + "? "); 
      answer = input.nextInt(); 
      ++wrong; 
      System.out.println("The number of attemt is " + wrong); 

     } 
+0

我輸入的代碼與您所做的一樣。當我輸入錯誤的答案時,我沒有得到輸出「嘗試次數爲1」 - – user3196297

+0

@ user3196297你會得到什麼? – laaposto

+0

我沒有得到輸出,因爲我沒有把++錯誤和System.out.println(「嘗試次數是」+錯誤),因此「嘗試的次數是1」。在while語句之後。非常感謝你 – user3196297

0

你需要增加錯誤,你顯示它之前:

import java.util.Scanner; 
public class Add { 
    public static void main(String[] args){ 
     Scanner input = new Scanner (System.in); 

     int num1 = (int)(Math.random() * 10); 
     int num2 = (int)(Math.random() * 10); 
     int wrong = 0 ; 

     System.out.println("What is " + num1 + "+" + num2 + "=" + "?"); 
     int answer = input.nextInt(); 

     while (num1 + num2 != answer){ 
      wrong++ ; 
      System.out.println("Wrong answer, Try again . What is " + num1 +"+"+ num2 + "? "); 
      answer = input.nextInt(); 
      System.out.println("The number of attempt is " + wrong); 

     } 
     System.out.println("You got it correct !"); 
    } 
}