如何在Java中修复此异常?
我的代码是这样的如何在Java中修复此异常?,java,file-io,Java,File Io,我的代码是这样的 import java.io.File; import java.util.Scanner; public class ReadFile{ public static void main(String[] args)throws Exception { Scanner scan = new Scanner(new File("input.txt")); int[][] arr = new int[4][4]; for
import java.io.File;
import java.util.Scanner;
public class ReadFile{
public static void main(String[] args)throws Exception {
Scanner scan = new Scanner(new File("input.txt"));
int[][] arr = new int[4][4];
for(int t = 1; t <= 2; t++){
int firstRow = scan.nextInt();
System.out.println(firstRow);
for(int i = 0; i <= 4; i++){
if(scan.hasNextLine()){
String[] splited = scan.nextLine().split("\\s");
for(String f : splited)
System.out.println(f);
for(int g = 0; g <= 4; g++){
arr[i][g] = Integer.parseInt(splited[i]); // at this point the exception is being thrown
}
}
}
}
}
基本上,我想读取第一个数字2(一行中的单个值)和3(第6行中从顶部开始的单个值),并将它们存储在firstRowNum变量和secondNumRow变量中,其余数字存储在两个4X4矩阵中。
但是当我运行代码时,我得到了以下异常
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:504)
at java.lang.Integer.parseInt(Integer.java:527)
at ReadFile.main(ReadFile.java:20)
我认为我没有正确设置循环
谢谢更换
splited[i]
与
作为Integer.parseInt()
的参数。另外,不要对g
索引使用另一个循环;使用
arr[i][g++]
并在每个循环的内部之前将g初始化为0。或者,按原样使用基于g的循环,但将splited[i]
替换为splited[g]
您还有其他问题,例如使用
i <= 4
i替换
splited[i]
与
作为Integer.parseInt()
的参数。另外,不要对g
索引使用另一个循环;使用
arr[i][g++]
并在每个循环的内部之前将g初始化为0。或者,按原样使用基于g的循环,但将splited[i]
替换为splited[g]
您还有其他问题,例如使用
i <= 4
i您可以在转换为整数
之前检查字符串
是否为空,使用函数您可以在转换为整数
之前检查字符串
是否为空,使用该功能时,您已经回答了问题,但即将点击Post您的答案:当您已经回答问题时,DWA将点击Post您的答案:Dfor(int i=0;ifor(int i=0;i