我尝试从文件中读取一个字符串,它工作正常,但它不适用于整数。我似乎无法找到问题
public static void main(String[] args) throws FileNotFoundException {
File in = new File ("FCITsamba.in.rtf");
Scanner scanner = new Scanner(in);// Scanner variable to read from the input file
File outFile = new File("FCITsamba.txt");// the out file
PrintWriter out = new PrintWriter(outFile); // Printwriter to write to the file
int maxAccounts = 0;//maximum number of accounts that can be in the bank
int maxTransactions = 0;//maximum number of transactions in a given day
int accNum = 0;
int transNum = 0;
int d = 0;
int k = 0;
int dayNo = 1;
if (!in.exists()) {
System.out.println("Input file, " + in + ", does not exist.");
System.exit(0);
}
maxAccounts = scanner.nextInt();
maxTransactions = scanner.nextInt();
d = scanner.nextInt(); //representing the number of days for the simulation
k = scanner.nextInt();
它给了我这个错误:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at fcitsamba.FCITsamba.main(FCITsamba.java:43)
Java Result: 1
我尝试输入一个inputMismatchException,但它没有用,我也尝试将它放在if语句中,如下所示:
if(scanner.hasNextInt()){
maxAccounts = scanner.nextInt();
maxTransactions = scanner.nextInt();
d = scanner.nextInt(); //representing the number of days for the simulation
k = scanner.nextInt();
}
但它没有效果
这是输入文件:
200
10000
2
11
OPENACCOUNT 1485 Aslam Saeed 2000.0
DEPOSIT 1485 1000.0
...
答案 0 :(得分:0)
当您从文件中读取文件时,它无法识别是否正在读取数字或字符串,因此所有内容都将被视为字符串,包括数据文件(200, 10000, 2, 11)
中显示的内容。
而不是写作:
d = scanner.nextInt();
试试这个:
d = Integer.parseInt(scanner.nextLine());