mardi 2 janvier 2018

Scanner: scan int or string

Trying to use the Scanner to take either an int or a string.. the code below is what I have:

System.out.println("where would you like to send the following item: ");
System.out.println("1. groceries, 2. savings, 3. utilities");
System.out.print("Enter list name or list number to send: ");
String user = user_input.nextLine();
      if (user.toLowerCase().equals("groceries") || Integer.parseInt(user) == 1) {
             System.out.println("item was sent to the grocery list");

      }else if(user.toLowerCase().equals("savings") || Integer.parseInt(user) == 2) {
             System.out.println("item was sent to the savings list");

      }else if(user.toLowerCase().contains("utilities") || Integer.parseInt(user) == 3) {
             System.out.println("item was sent to the utilities list");

      }else{
             System.out.println("item is not in any category");

      }

My issue is that I keep getting a NumberFormatException error whenever I type in a String. Typing an int doesn't give me any problems. I thought taking the input using String user = user_input.nextLine(); and converting a number string to an int in the if statement using Integer.parseInt(user) would do the trick but it's still giving me the error message.

Any help is greatly appreciated...

Aucun commentaire:

Enregistrer un commentaire