2014-11-06 46 views
0

比如我有如下的簡單的程序:「多少次將你玩」我如何根據用戶輸入的值循環/重複程序?

Scanner guess = new Scanner(System.in); 
Scanner play = new Scanner(System.in); 

int count =0; 
int sum=0; 
int num, N; 
int ply, T; 

System.out.println("How many times will you play?"); 
T = play.nextInt(); 



System.out.println("How many numbers will you enter?"); 
N = guess.nextInt(); 



for(count =0; count < N; count++) 
{ 
    System.out.println("Enter a number"); 
    num = guess.nextInt(); 
    sum +=num; 
} 

    System.out.println("The sum of the numbers entered is:"+sum); 

我如何重複/循環從「輸入號碼」程序開始,底座上

這意味着程序將基於之前的用戶輸入值重複。

例如, 用戶輸入要播放5次 然後程序將重複/循環5次從輸入數字開始。

請幫助我......謝謝你..你是個天才。

回答

2

你基本上已經回答自己:

只是做另一個用於在T變量(應該有一個小寫的名稱BTW)循環:

System.out.println("How many times will you play?"); T = play.nextInt(); 

for (int playNum = 0; playNum < T; playNum++) 
{ 
    sum = 0; // Don't forget to reset sum on each iteration 
    System.out.println("How many numbers will you enter?"); N = guess.nextInt(); 

    for(count =0; count < N; count++) 
    { 
     System.out.println("Enter a number"); 
     num = guess.nextInt(); 
     sum +=num; 
    } 
    System.out.println("The sum of the numbers entered is:"+sum); 
} 
+0

謝謝!終於搞清楚了......我錯過了玩法計數的整數。你真棒!謝謝! – Rain 2014-11-07 00:05:45

2

你只需要一個Scanner。你的變量名稱有點混亂(我更喜歡更有限的詞法範圍)。最後,你可以使用循環。像,

Scanner scan = new Scanner(System.in); 
System.out.println("How many times will you play?"); 
int plays = scan.nextInt(); 
for (int playCount = 0; playCount < plays; playCount++) { 
    System.out.println("How many numbers will you enter?"); 
    int numbers = scan.nextInt(); 
    int sum = 0; 
    for (int count = 0; count < numbers; count++) { 
     System.out.println("Enter a number"); 
     int num = scan.nextInt(); 
     sum += num; 
    } 
    System.out.println("The sum of the numbers entered is:" + sum); 
} 
+0

謝謝!終於搞清楚了......我錯過了玩法計數的整數。你真棒!謝謝! – Rain 2014-11-07 00:10:48

相關問題