[英]beginner java - printing tables
我正在打印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
這將完成工作:
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();
}
問題是你只在運行內部后增加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。
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();
}
}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.