我如何根据用户输入的值循环/重复程序?

时间:2014-11-06 19:31:02

标签: java eclipse

示例我有如下简单程序:

 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 个答案:

答案 0 :(得分:2)

你基本上已经回答了自己:

在T变量上执行另一个for循环(它应该具有小写名称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);
}

答案 1 :(得分: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);
}