解析数字抛出:线程中的异常 "main" java.lang.NumberFormatException:对于输入字符串

Parsing a number throws: Exception in thread "main" java.lang.NumberFormatException: For input string

我正在制作一个面向对象的程序,它采用对象类型 Date 的数组并将其写入文件。但是我在解析数字时遇到问题。我看不到我的 intString 变量在哪里混淆了:

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 输入我的字符串吧?那么为什么我会收到此错误?

问题出在您的文件上。 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

祝你有愉快的一天

问题出在这一行:

fin = new Scanner(fileName);

您正在从字符串文件名创建扫描仪。这是您输入的文件路径。不是文件本身。您在上面几行正确地创建了 fin Scanner。再做同样的事情。