有人能给我解释一下为什么我会犯捕捉错误吗?
我正在尝试从传入args的文件中读取值(数字)。
我也不太明白问题从何而来。
import java.util.Scanner;// Import the Scanner class to read text files
import java.io.File;// Import the File class
import java.io.FileNotFoundException;// Import this class to handle errors
import java.io.*;
public class main extends GeneralMethods {
public static void main(String[] args) {
if (args.length <= 1 || args.length > 2) {
println("Error, usage: software must get two input files");
System.exit(1);
}
String file_name1 = args[0]; // data to insert
String file_name2 = args[1]; // data to check
File data_to_insert = new File(file_name1);
File data_to_check = new File(file_name2);
Scanner input = new Scanner(System.in); // Create a Scanner object
println("Enter hashTable size");
int hashTable_size = input.nextInt(); // Read hashTable_size from user
println("Enter num of hashing function");
int num_of_has = input.nextInt(); // Read num of hashing from user
hashTable T = new hashTable(hashTable_size);
println("hashTable before insert values\n");
T.printHashTable();
input.close();
int i = 0;
try {
input = new Scanner(data_to_insert);
String data;
while ((data = input.next()) != null) {
T.set(i, Integer.parseInt(data));
i++;
}
input.close();
} catch (Exception e) {
System.out.println("\nError: Reading, An error occurred while reading input files. Check your input type");
e.printStackTrace();
}
T.printHashTable();
}
}
这是我的输出
打印捕获错误
hashTable before insert values
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
Error: Reading, An error occurred while reading input files. Check your input type
java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1478)
at main.main(main.java:36)
[1,2,3,4,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
1条答案
按热度按时间lf3rwulv1#
在这条线上,
scanner的next()方法在没有更多数据的情况下不会返回null,而是抛出您得到的nosuchelementexception。
使用此选项检查更多数据:
方法hasnext()按预期返回true或false。