gpt4 book ai didi

java - 在Java中创建数字矩阵

转载 作者:行者123 更新时间:2023-12-01 06:11:45 25 4
gpt4 key购买 nike

我正在尝试编写一个程序,提示用户输入 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);

}
}

最佳答案

需要在循环开始时重置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 循环会更好。

关于java - 在Java中创建数字矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33072786/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com