1

我正在打印 0-99 的值和食物数组中的随机字符串。我似乎无法正确地将它们输出到表格中。

String foods[] = {"Bread", "Pizza", "Cheese"};
for (int x = 0; x<=99; x++) {
      for (int i = 0; i<4; i++) {
          int random = (int) (Math.random() * 3);
          System.out.print(x + " - " + foods[random] + "\t\t");
      }
    System.out.println();
}

实际输出:

0 - Pizza      0 - Bread     0 - Cheese    0 - Bread
1 - Bread      1 - Pizza     1 - Bread     1 - Pizza
.... until 99

预期输出:

0 - Pizza      1 - Bread     2 - Cheese    3 - Bread
4 - Bread      5 - Pizza     6 - Bread     7 - Pizza
.... until 99
4

3 回答 3

2

这将完成这项工作:

    String foods[] = {"Bread", "Pizza", "Cheese"};
    for (int x = 1; x<=100; x++) {

              int random = (int) (Math.random() * 3);
              System.out.print((x-1) + " - " + foods[random] + "\t\t");
              if(x%4==0)
                  System.out.println();


    }
于 2013-09-29T22:10:31.687 回答
1

问题是您仅在内部 for 运行并打印整行之后才增加 x 。

String foods[] = {"Bread", "Pizza", "Cheese"};
    for (int x = 0; x <= 99; ) {
        for (int i = 0; i < 4; i++) {
            int random = (int) (Math.random() * 3);
            System.out.print(x + " - " + foods[random] + "\t\t");
             x++;
        }
        System.out.println();
    }

您必须在内部 for 内增加 x。

于 2013-09-29T22:11:43.117 回答
0

试试这个代码

import java.io.*;
class dev
{
public static void main (String[] args)
{
   String foods[] = {"Bread", "Pizza", "Cheese"};
        for (int x = 0; x<=99; x++) 
          {
             System.out.print(x + "  -" + foods[ (int) (Math.random() * 3)] + " \t\t");
              if(x%4==0) System.out.println();
           }
 }}
于 2013-09-29T22:16:33.440 回答