【问题标题】:A method has infinite loops方法有无限循环
【发布时间】:2015-04-26 12:29:19
【问题描述】:

我正在尝试编写一个方法,该方法使用Scanner 类根据每行中的项目数填充矩阵中Number 类型的对象。这是我试图做的(其中有问题,因为它看起来包含无限循环):

public void fillMatrix ( ) {
    Number n;
    ArrayList<Number> nums;
    int num1;
    System.out.println("enter number of matrix elements :");
    num1 = sc.nextInt();

    for (int i = 0; i < rows; i++) {
        nums = new ArrayList<>();

        for (int j = 0; j < cols; j++) {
            n = new Number();

            System.out.println("enter the numerator of number(" + i + "," + j + "):");
            n.setNumerator(sc.nextInt());
            System.out.println("enter the denominator of number(" + i + "," + j + "):");
            n.setDenominator(sc.nextInt());
            nums.add(n);
        }
        matrix.put(i, nums);
    }
}

【问题讨论】:

  • rows 和 cols 的定义在哪里?他们的价值观是什么?
  • 您从键盘获得 num1 但您不使用它。你需要那个循环吗?
  • 公共类矩阵 { Scanner sc = new Scanner(System.in);;私有 HashMap > 矩阵;公共静态整数行,列; public Matrix (int rows, int cols){ matrix = new HashMap > (); this.rows =行; this.cols=cols; } @JFPicard 这包括行和列的定义
  • @Shondeslitch num1 是获取矩阵的元素个数
  • @user233531 但你不会将它用于任何事情。无论 n1 的值如何,您总是从键盘执行相同数量的输入。

标签: java object for-loop methods java.util.scanner


【解决方案1】:

首先 - 你没有创建一个名为 sc 的新扫描仪对象。

Second - 未定义行和列。全局变量通常是不好的做法(参见:What kind of global variable is bad practice in java?

也没有无限循环,因为每个 for 循环都会在 i 到达行时结束。

【讨论】:

  • 这是上一部分:Scanner sc = new Scanner(System.in);;私有 HashMap > 矩阵;公共静态整数行,列; public Matrix (int rows, int cols){ matrix = new HashMap > (); this.rows =行; this.cols=cols;
  • @user233531 那么你不关闭扫描仪吗?这可能是你认为你有“无限循环”的原因,而问题可能是你的程序总是在等待一个新的输入。
  • @user233531 shondeslitch 是正确的,一旦你输入了所有的输入它就会停止结束。
  • 当我关闭扫描仪时出现错误,如何显示整个班级代码?
猜你喜欢
  • 1970-01-01
  • 2015-12-28
  • 1970-01-01
  • 1970-01-01
  • 2020-02-26
  • 2013-09-17
  • 1970-01-01
  • 1970-01-01
  • 2022-08-15
相关资源
最近更新 更多