初学者java - 打印表

时间:2013-09-29 22:03:03

标签: java arrays

我正在打印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

3 个答案:

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


    }

答案 1 :(得分:1)

问题是你只在运行内部之​​后递增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();
    }

你必须在内部增加x。

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