如何解决thread main中的异常?出了什么问题?

How do I solve the exception in thread main? what is going wrong?

我尝试编写一个小程序,但它一直收到错误消息:

Exception in thread "main" java.lang.NumberFormatException: For input string: "hallo"
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at TheNoteBook.main(TheNoteBook.java:7)

我真的不明白这是怎么回事。我使用 Eclipse。

import java.util.Scanner;
public class TheNoteBook {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        int t = Integer.parseInt( in.nextLine() );
        for(int c=0; c<t; c++){
            String word = in.nextLine();
            Note note = new Note(word);
            System.out.println("Note " +c+ " says: " + note.getContent() ); 


       }

    }

您的代码运行良好。你只是给了程序错误的输入。

NumberFormatException 表示,您正试图将某些内容转换为非数字的数字。在您的情况下,您尝试将 hallo 转换为数字。

因此您正在尝试解析一个整数,但您的输入是一个字符串 hallo。您的 class 应该如何将 hallo 转换为数字?因此,您可能首先尝试输入一个字符串,而您 的第一个输入必须是一个数字 .

顺便说一句,您应该使用 nextInt() 方法来获取数字输入而不是 nextLine()

Scanner in = new Scanner(System.in);

        int t = in.nextInt();
        in.nextLine();
        for (int c = 0; c < t; c++)
        {
            String word = in.nextLine();
            Note note = new Note(word);
            System.out.println("Note " + c + " says: " + note.getContent());
        }