我正在制作一个面向对象的程序,它接受一个对象类型Date
的数组并将其写入文件。但我在解析数字时遇到问题。我无法看到int
和String
变量混淆的位置:
public static Date[] createMe() throws FileNotFoundException
{
Scanner kb = new Scanner(System.in);
System.out.print("please enter the name of the file: ");
String fileName= kb.nextLine();
Scanner fin = new Scanner(new File(fileName));
int count = 0;
while (fin.hasNextLine()){
count++;
fin.nextLine();
}
fin.close();
Date[] temp = new Date[count];
fin = new Scanner(fileName);
while(fin.hasNextLine()){
String line = fin.nextLine();
String[] s = line.split("/");
int month = Integer.parseInt(s[0]);
int day = Integer.parseInt(s[1]);
int year = Integer.parseInt(s[2]);
}
return temp;
}
我一直收到此错误代码,我不知道原因:
please enter the name of the file: Track.java
Exception in thread "main" java.lang.NumberFormatException: For input string: "Track.java"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at Date.createMe(Date.java:49)
at DateTester.main(DateTester.java:28)
我应该只用我的Scanner kb
输入我的字符串吧?那我为什么会收到这个错误?
答案 0 :(得分:1)
问题在于这一行:
fin = new Scanner(fileName);
您正在从字符串文件名创建扫描程序。您键入的文件的路径是什么。不是文件本身。你创建了fin Scanner正确的几行。再做一遍。
答案 1 :(得分:0)
问题在于您的文件。 java文件不以数字开头。这是一个工作正常的例子(我添加了try(子句)来安全地释放文件资源):
public static Date[] createMe() throws FileNotFoundException {
try (PrintWriter out = new PrintWriter("filename.txt")) {
out.print("3/1/12");
}
try (Scanner kb = new Scanner(System.in)) {
String fileName = "filename.txt";
int count = 0;
try (Scanner fin = new Scanner(new File(fileName))) {
while (fin.hasNextLine()) {
count++;
fin.nextLine();
}
}
Date[] temp = new Date[count];
try (Scanner fin = new Scanner(new File(fileName))) {
while (fin.hasNextLine()) {
String line = fin.nextLine();
String[] s = line.split("/");
int month = Integer.parseInt(s[0]);
int day = Integer.parseInt(s[1]);
int year = Integer.parseInt(s[2]);
System.out.println(month + " " + day + " " + year);
}
}
return temp;
}
该计划的结果:
please enter the name of the file: 3 1 12
度过愉快的一天