Search code examples
javamultithreadingexceptionprogram-entry-point

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


I tried to write a small program, but it keeps getting an arror message:

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)

I really don't understand what is going on. I use 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() ); 


       }

    }

Solution

  • Your code works fine. You are just giving the program the wrong input.

    NumberFormatException means, you are trying to convert something to a number that is no number. In your case, you tried to convert hallo to a number.

    So you are trying to parse an integer, but your input is a String hallo. How is your class supposed to convert hallo to a number? So you probably tried entering a String first, while your very first input must be a number.

    By the way, you should use the nextInt() method to get a number input rather than 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());
            }