用Java创建数字矩阵

鲨鱼

我正在尝试编写一个程序,该程序将提示用户输入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循环来代替。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章