如何使用循环将随机整数打印到多行?

时间:2015-10-25 07:35:58

标签: java loops

我正在尝试创建一个程序,在用户选择的每次迭代中输出3个随机整数。当我执行以下操作时,我的所有数字都在同一行。如何运行循环以便每行输出3个整数?

if (yourNumber == 3){
    while (playTimes > print){
        for (int i = 0; i < 3; i++){
            int pick = randomLotto.nextInt(10);
            sum += pick;
            System.out.print(pick + " ");
        }
    print++;
    }
}
System.out.println();
System.out.println("Sum = " + sum);

这是输出:

4 9 3 3 1 3   
Sum = 23

4 个答案:

答案 0 :(得分:1)

编辑:误读了这个问题。原始答案已删除。

您的System.out.println()位于错误的行。移动它以便它在for块结束后直接移动。

答案 1 :(得分:1)

while (playTimes > print)
{
   for (int i = 0; i < 3; i++)
   {
      int pick = randomLotto.nextInt(10);
      sum += pick;
      System.out.print(pick + " ");
   }
   System.out.println(); //this is the point you are missing
   print++;
}

答案 2 :(得分:1)

您的while循环似乎也缺少右括号。这应该这样做:

public static void main(String[] args) {
    Random randomLotto = new Random();

    int yourNumber = 3;
    int print = 0;
    int playTimes = 3;
    int sum = 0;

    if (yourNumber == 3) {
        while (playTimes > print) {
            for (int i = 0; i < 3; i++) {
                int pick = randomLotto.nextInt(10);
                sum += pick;
                System.out.print(pick + " ");
            }
            System.out.println();
            print++;
        }
    }
    System.out.println();
    System.out.println("Sum = " + sum);
}

答案 3 :(得分:0)

每次迭代,您可以将每个随机数存储在一个单独的变量中,并在println语句中使用这些变量。以下代码未经过测试,但应根据您的要求进行测试。

for (int i = 0; i < 3; i++){
  int pick_1 = randomLotto.nextInt(10);
  int pick_2 = randomLotto.nextInt(10);
  int pick_3 = randomLotto.nextInt(10);
  sum = sum + pick_1 + pick_2 + pick_3;
  System.out.println(pick_1 + " "+ pick_2 + " " + pick_3);
}