我试图将某些数据类型的输入存储到变量中并将它们打印到输出文件中,但我的代码似乎不起作用。如果我使用System.in Scanner通过std输入输入并打印到stdout,我的代码将起作用。但是,当我尝试我拥有的东西时,我会继续这样做:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at Queue.main(Queue.java:17)
这是我的代码:
import java.util.*;
import java.io.*;
public class Queue {
public static void main(String[] args) throws IOException {
// open files
// takes input from test-input.txt
Scanner input = new Scanner(new File("test-input.txt"));
// prints output to test-output.txt
PrintWriter output = new PrintWriter(new FileWriter("test-output.txt"));
//Scanner input = new Scanner(System.in);
while (input.hasNextLine()) {
int teller = input.nextInt();
String name = input.next();
int simTime = input.nextInt();
int transTime = input.nextInt();
output.println(teller + " " + name + " " + simTime + " " + transTime);
}
// close files
input.close();
output.close();
}
}
我的输入文件包含以下行:
1 Jesse 2 9
2 Wilson 1 4
3 King 4 8
4 Andy 6 7
答案 0 :(得分:0)
尝试确保解析非空行,如果您的文件有额外的空行,可能会发生这种情况,所以我建议您在while
语句中进行检查
while (input.hasNextLine()) {
final String line = input.nextLine().trim();
if (line.isEmpty()) continue; // continue if line is empty
String [] items = line.split("\\s+");
int teller = Integer.parseInt(items[0]);
String name = items[1];
int simTime = Integer.parseInt(items[3]);
int transTime = Integer.parseInt(items[3]);
output.println(teller + " " + name + " " + simTime + " " + transTime);
}