【发布时间】:2015-10-12 03:21:40
【问题描述】:
我正在尝试编写一个程序,它会提示用户输入 1 到 9 之间的数字,并将创建一个 x x 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);
}
}
【问题讨论】: