有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

异常处理NumberFormatException(Java)

有人能告诉我为什么会出现“NumberFormatException”错误吗? 我的程序要求我输入10个整数,然后将其写入一个文件中,并能被读回并一起求平均值

我可以很好地输入和写入文件,但我遇到了以下错误:

线程“main”java中出现异常。lang.NumberFormatException:对于输入字符串:“输入的整数:1” 在爪哇。lang.NumberFormatException。forInputString(未知源) 在爪哇。整型。parseInt(未知源) 在爪哇。整型。parseInt(未知源) 平均来说。平均的readRecords(平均值:99) 平均来说。平均的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();
            }
        }
}

共 (2) 个答案

  1. # 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. # 2 楼答案

    如果您使用字符串作为输入,可能必须尝试使用 在解析之前的空白空间{{CD1}}。