0

I have been learning java language from many sources (recently mainly from mooc.fi) and today I again encounter problem with else and if else statement. There is my code:

import java.util.Scanner;

public class Main {

     public static void main(String[] args) {
     Scanner reader=new Scanner(System.in);
        while (true) {
        System.out.println("Choose operation:\n[1] Add xx\n[2] Add yyy\n[x] 
Exit");
        String text = reader.nextLine();
        if (text.equals("x")) {
            break;
        }else if (Integer.parseInt(text) == 1) {
            //xxx         
        } else if (Integer.parseInt(text) == 2) {
            //xxx
        } else 
            System.out.println("Wrong character");
        }
    }
}

There is problem with Exception in thread "main" java.lang.NumberFormatException: For input string: (all characters in keyboard excluding X and numbers).

The most interesting (for me) part is conduct program without else if contains:

else if (Integer.parseInt(text) == 1), when program runnig well.

It seems to be problem with else after checking if variable text contains parseInt. Can you help me solve this problem? I feel that there is big hole in my mind about this situation. Best Regards!

rudzik12
  • 1
  • 1
  • Why not simply `"1".equals(text)`? There isn't really a reason to parse it to an integer. – Ivar Feb 10 '18 at 17:57
  • Thank you. I change my code and now it's working fine. However, I still don't know why program throw exception as above, so if anybody want to share knowledge in that case I would by glad to hear answer. – rudzik12 Feb 10 '18 at 20:15
  • If I understand you correctly, you wonder why a you cant parse a string when it is not a number? I don't really see what that would be weird. You can't `parseInt` a text _because_ it is not an integer. – Ivar Feb 10 '18 at 20:36

0 Answers0