gpt4 book ai didi

java - 我正在使用分数库读取文件,但在线程 "main"java.lang.ArrayIndexOutOfBoundsException : 0 中出现异常

转载 作者:太空宇宙 更新时间:2023-11-04 11:02:14 25 4
gpt4 key购买 nike

 public static void readFile() {

int num, den;
int row = 0, column = 0;

File file = new File("C:\\Users\\camil\\IdeaProjects\\LAB1-434\\src\\MatrixA.txt");
try {
Scanner sc = new Scanner(file);
fRow = sc.nextInt(); to get the size of my matrix
fCol = sc.nextInt();
while (sc.hasNextInt()) {
for (row = 0; row < fRow; row++) {
for (column = 0; column < fCol; column++) {

num = sc.nextInt();
den = sc.nextInt();

Fraction[][] fArray = new Fraction[row][column];
Fraction f = new Fraction(num, den);

System.out.print("|" + f + "| "); ** just to test it and it is reading the values correctly**

fArray[row][column] = f; **im getting the error at these two lines**
System.out.print(fArray[row][column]);
}
System.out.println();
}
}
**...**

我的文本文件看起来像这样(前两行是大小,其余的 1 是分子,另一行是分母)

3 3
1 8 1 7 1 2
1 8 1 3 1 13
1 3 1 8 1 16

在测试我的代码而不尝试生成新数组时,它工作得很好,但是当我添加最后两行时,出现数组越界错误

最佳答案

以下代码在开头创建一个空数组(行=0 和列=0)。

Fraction[][] fArray = new Fraction[row][column];

因此,后续初始化会给出 java.lang.ArrayIndexOutOfBoundsException

fArray[row][column] = f; 

看起来这是编码时的疏忽;可能应该编码为:

Fraction[][] fArray = new Fraction[fRow][fCol];

关于java - 我正在使用分数库读取文件,但在线程 "main"java.lang.ArrayIndexOutOfBoundsException : 0 中出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46775014/

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