【问题标题】:NumberFormatException (Java)NumberFormatException (Java)
【发布时间】:2016-03-09 23:25:20
【问题描述】:

谁能告诉我为什么会收到“NumberFormatException”错误? 我的程序要求我输入 10 个整数,然后将它们写入一个文件,并且能够被读回并一起平均。

我可以很好地输入和写入文件,但是我得到了这个错误:

线程“main”java.lang.NumberFormatException 中的异常:对于输入字符串:“输入的整数:1” 在 java.lang.NumberFormatException.forInputString(未知来源) 在 java.lang.Integer.parseInt(未知来源) 在 java.lang.Integer.parseInt(未知来源) 平均.Average.readRecords(Average.java:99) 平均.Average.main(Average.java:29)

for (int i = 0 ; i < 10 ; i++) {
             System.out.printf("Please enter integer %d: ", i+1);
             numbers[i] = input.nextInt();

             {
                 try
                 {
                    output.format("Inputted integer: %s%n", String.valueOf(numbers[i])); 
                 }
                 catch (FormatterClosedException formatterClosedexception)
                 {
                     System.err.println("Error writing to the file. Terminating.");
                     break;
                 }
                 catch (InputMismatchException inputMismatchException)
                 {
                     System.err.println("Please restart the program and enter integers ONLY.");
                     break;
                 }
                 catch (NumberFormatException numberFormatException)
                 {
                     System.out.print("Check for numbers.txt and see what ya got!");
                 }

完整代码...

import java.util.Scanner;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.SecurityException;
import java.nio.file.NoSuchFileException;
import java.util.Formatter;
import java.util.FormatterClosedException;
import java.util.NoSuchElementException;
import java.util.InputMismatchException;




public class Average {

    private static Formatter output;

    static Scanner input = new Scanner(System.in);
    static int[] numbers = new int[10];

    public static void main(String[] args)
        {
            openFile();
            addRecords();
            closeFile();
            readRecords();
        //   closeFile();
        }
        public static void openFile()
        {
            try
            {
                output = new Formatter("numbers.txt");
            }
            catch (SecurityException securityException)
            {
                System.err.println("Write permission denied. Terminating.");
                System.exit(1);
            }
            catch (FileNotFoundException fileNotFoundException)
            {
                System.err.println("Error opening file. Terminating.");
                System.exit(1);
            }
        }
        public static void addRecords()
        {  
            System.out.print("Hello, welcome to my program!\n");

            for (int i = 0 ; i < 10 ; i++) {
                 System.out.printf("Please enter integer %d: ", i+1);
                 numbers[i] = input.nextInt();

                 {
                     try
                     {
                        output.format("Inputted integer: %s%n", String.valueOf(numbers[i]));
                     }
                     catch (FormatterClosedException formatterClosedexception)
                     {
                         System.err.println("Error writing to the file. Terminating.");
                         break;
                     }
                     catch (InputMismatchException inputMismatchException)
                     {
                         System.err.println("Please restart the program and enter integers ONLY.");
                         break;
                     }
                     catch (NoSuchElementException elementException)
                     {
                         System.err.println("Invalid input. Please try again.");
                         input.nextLine();
                     }
                     catch (NumberFormatException numberFormatException)
                     {
                         System.out.print("Check for numbers.txt and see what ya got!");
                     }
                     //System.out.print("? ");
                 }
             }
        }
        public static void closeFile(){
            {
                if (output != null)
                    output.close();
            }
       }
       public static void readRecords()
       {   
            try (BufferedReader br = new BufferedReader (new FileReader("numbers.txt"))){
                String line;
                int[] number = new int[10];
                int i=-1;
                while((line = br.readLine())!= null){
                    i++;
                    number [i] = Integer.parseInt(line);
                    System.out.println("number" +i+" = " +number[i]);
                }
            }
            catch (NoSuchFileException noSuchFileException)
            {
                System.out.print("This file was not created properly and cannot be found.");
            }
            catch (IllegalStateException illegalStateException)
            {
                System.out.print("Error reading from file. Terminating");
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
}

【问题讨论】:

  • 为什么不直接使用%d
  • 请显示一个实际的控制台脚本,其中包含您的输入和输出以及整个堆栈跟踪。我怀疑错误出现在输入1之后的输入行上。
  • 您在此处发布的任何内容看起来都不会引发NumberFormatException。打印堆栈跟踪并仔细检查它的来源。我的赌注是readRecords(),您正在尝试解析来自numbers.txt 的行,但这都是猜测,直到您充实您的问题。
  • @JimGarrison imgur.com/xd9y0AN
  • @azurefrog imgur.com/xd9y0AN

标签: java exception-handling int try-catch numberformatexception


【解决方案1】:

所以,问题实际上出在您的 readRecords 方法中,您正在读取 Inputted integer: 1,然后尝试将值解析为 int,但显然不是

您需要从文本中提取数字,可能使用类似...

while ((line = br.readLine()) != null) {
    i++;
    String[] split = line.split(":");
    line = split[1].trim();
    number[i] = Integer.parseInt(line);
    System.out.println("number" + i + " = " + number[i]);
}

【讨论】:

    【解决方案2】:

    如果您使用字符串作为输入,也许您必须尝试使用 mystring.trim() 尝试解析之前的空格。

    【讨论】:

    • 这应该是评论,而不是答案。我知道,你没有代表。不要通过发布 cmets 作为答案来滥用系统。这样做会更难找到发布 cmets 所需的代表。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-25
    • 2014-11-06
    • 1970-01-01
    相关资源
    最近更新 更多