基本上,我有一个文本文件,其中的行对应于对象描述(对象的变量)。我的意思是,例如,一行可能看起来像: 字符串 int int double int long。 现在,我有一个这些类型的对象的空数组。 我的目标是将对象从文本文件传输到数组。我已经寻找解决方案,但我没有找到任何东西。 这是我尝试做的。我得到了 java.util.InputMismatchException 尽管我不知道如何解决这个问题。非常感谢您的帮助。
Scanner transfer = new Scanner (new FileInputStream(a));
// we use a simple for loop to set every variable of the object to the file's order.
for (int i = 0 ; i< Array.length; i++){
Array[i].setLong(transfer.nextLong());
Array[i].setString(transfer.next());
Array[i].setInt(transfer.nextInt());
Array[i].setString(transfer.next());
Array[i].setDouble(transfer.nextDouble());
Array[i].setInt(transfer.nextInt());
}
transfer.close();
编辑2第一次传输时发生的新堆栈跟踪
Exception in thread "main" java.lang.NullPointerException
at Driver.main(Driver.java:31)
最佳答案
只需尝试放入几个带有 else 子句的 if 语句,打印 if 是否有效...
if(transfer.hasNextDouble()){
Array[i].setDouble(transfer.nextDouble());
}else{
System.out.println("expecting a double, but got"+transfer.getNext());
}
if(transfer.hasNextLong()){
Array[i].setLong(transfer.nextLong());
}else{
System.out.println("expecting a Long, but got"+transfer.getNext());
}...
等等...这样你就会知道出了什么问题
Scanner transfer = new Scanner (new FileInputStream(a));
// we use a simple for loop to set every variable of the object to the file's order.
for (int i = 0 ; i< Array.length; i++){
Scanner s2= new Scanner(transfer.nextLine())
Array[i].setLong(s2.nextLong());
Array[i].setString(s2.next());
Array[i].setInt(s2.nextInt());
Array[i].setString(s2.next());
Array[i].setDouble(s2.nextDouble());
Array[i].setInt(s2.nextInt());
s2.close();
}
transfer.close();
这很难看,但这可能是您原来的扫描仪无法进入下一行的问题。但如果没有文件和代码则无法确定。
将以下内容添加到您的代码中:
1) 验证扫描仪的行数与阵列的条目数相同
int count;
for(count=0; transfer.hasNextLine(); transfer.nextLine()){}
System.out.println(count==Array.length);
2) 验证每行有 6 个值 //我假设你能做到这一点。只需使用 string.split(delimeter) 并计算结果数组的长度
3) 验证每行是否具有您指定的类型
for (int i = 0 ; i< Array.length; i++){
Scanner s2= new Scanner(transfer.nextLine())
boolean hasLong= s2.hasNextLong();
//consume the input
s2.next();
\\next is a string so skip it
s2.next();
boolean hasInt= s2.hasNextInt();
//consume the input
s2.next();
s2.next();
boolean hasDouble=s2.hasNextDouble();
s2.next();
boolean hasInt2= s2.hasNextInt();
//consume the input
s2.next();
boolean allTrue=hasLong&&hasInt&&hasDouble&&hasInt2;
if(!allTrue){
//print the line number so you can check where the issue is in the file
System.out.println("error on line: "+i);
//print the values of the booleans if you want
}
s2.close();
}
transfer.close();
这应该是一个足够好的开始
关于java - 将不同类型的数据从文本文件传输到对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35906016/