我正在尝试编写一个程序,它将提示用户输入1到9之间的数字,并将创建一个矩阵x x,其中x是给定的数字。它应该产生从1到x ^ 2的随机数来填充矩阵。我找到了它,如果我输入'5'我得到一行5个随机数字然后四行只有一个数字。我错过了什么?
import java.util.Scanner;
import java.util.Random;
public class MatrixFiller
{
public static void main(String[] args)
{
//Getting input from the user
Scanner input = new Scanner(System.in);
System.out.print("Size of Matrix(a number between 1 and 9): ");
int matrixn = input.nextInt();
input.close();
//max is the largest possible number that can be calculated
//with the given number squared.
int max = (matrixn * matrixn);
//Counters for building the matrix
int i = 0;
int j = 0;
//Will create a line with x numbers on it but then produces
//x lines with only one number. If given 5 it produces a
//line with 5 numbers then four more lines with one number
//each.
do {
do {
Random rand = new Random();
int mout = rand.nextInt(max - 0);
System.out.print(mout + " ");
i++;
}
while (i < matrixn);
System.out.println();
j++;
}
while (j < matrixn);
}
}
答案 0 :(得分:0)
您需要在循环开始时重置i
,否则它仍然是前一行的matrixn
。
do {
i = 0; // It won't work without this
do {
Random rand = new Random();
int mout = rand.nextInt(max - 0);
System.out.print(mout + " ");
i++;
} while (i < matrixn);
System.out.println();
j++;
} while (j < matrixn);
虽然这有效,但使用for
循环会更好。
答案 1 :(得分:0)
关键是在第一个i
循环的顶部将do
的值重置为零。
或者您可以使用for
循环,因为它似乎更清洁:
Random rand = new Random();
for (i=0; i<matrixn; i++) {
for (j=0; j<matrixn; j++) {
int mout = rand.nextInt(max);
System.out.print(mout + " ");
}
System.out.println();
}
答案 2 :(得分:-1)
你的内循环只执行一次,我必须从每次请求开始。
do{
i = 0 ;
do {
Random rand = new Random();
int mout = rand.nextInt(max – 0);
System.out.print(mout + “ “);
i ++;
} while(i<matrixn);
system.our.println();
j++;
} while(j < matrixn);