【问题标题】:Create number matrix in Java在Java中创建数字矩阵
【发布时间】: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);

  }
}

【问题讨论】:

    标签: java loops matrix


    【解决方案1】:

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

    【讨论】:

    • 谢谢!我不认为我们涵盖了重置循环。我试图找到一种方法在这里早些时候给你发一个下午,但它没有特色:/
    • 没问题。您应该尝试习惯使用for 循环。代码是for (int i = 0; i &lt; matrixn; i++) { ... }i0 开始。
    【解决方案2】:

    关键是在第一个 do 循环的顶部将 i 的值重置为零。

    或者您可以使用 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();
    }
    

    【讨论】:

    • 是否需要指定随机范围? int mout = rand.nextInt(max -min) ?
    • 范围在API中定义为[0..max)。我删除了- 0,因为它是多余的。
    【解决方案3】:

    你的内循环只执行一次,i每次都必须从乞求开始。

      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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-11
      • 1970-01-01
      • 2017-02-01
      • 1970-01-01
      • 2014-06-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多