【发布时间】: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