1

I want to accept user input as either an integer or a string in Java but I always get an error no matter what I do.

My code is very simple (I'm a beginner):

    System.out.println(
      "Enter the row number (or enter e to quit the application):"
    );

    Scanner rowInput = new Scanner(System.in);
    int row1 = rowInput.nextInt();

I want the user also to be able to press "e" to exit.

I have tried several things:

1) To convert row1 to a String and and say:

    if((String)(row1).equals("e"){
    System.out.println("You have quit") }

2) To convert "e" to an integer and say:

    if(row1 == Integer.ParseInt("e"){
    System.out.println("You have quit") }

3) To do the switch statement but it said I had incompatible types (String and an int).

My errors usually say: Exception in thread "main" java.util.InputMismatchException

Is there somebody who could help me?

Many thanks in advance!

Rob Kielty
  • 7,958
  • 8
  • 39
  • 51
user2399525
  • 91
  • 1
  • 1
  • 7

6 Answers6

2

You can try something like this

    Scanner rowInput = new Scanner(System.in);
    String inputStr = rowInput.nextLine();

    try{
        int row1 = Integer.parseInt(inputStr);
    } catch (NumberFormatException e) //If exception occurred it means user has entered 'e'
    {
        if ("e".equals(inputStr)){
            System.out.println("quiting application");
        }
     }

you should read the input from your scanner as String type and the try to convert that String input into integer using Integer.parseInt().

If its successful in parsing, it means user has input an Integer. And If it fails, it will throw an exception NumberFormatException which will tell you that its not an Integer. So you can go ahead and check it for e if it is, do whatever you want as per your requirement.

sakura
  • 2,249
  • 2
  • 26
  • 39
  • @StephenC agree!! modified with NFE. Although, I had explained it in words but missed to modify the code. – sakura Apr 12 '14 at 11:13
0

1) you should say Integer.parseInt() instead of Integer.ParseInt()

2) if you pass "e" to Integer.parseInt() you'll get java.lang.NumberFormatException

3) get your input as a string this way (cause it's safer)*:

Scanner rowInput = new Scanner(System.in);
String row = rowInput.next();
if (row.equals("e")) {
    //do whatever
}
else if(row.matches("\\d+$")) {
    //do whatever
}

*In your approach if user enters a non-integer input you'll encounter java.util.InputMismatchException

Mohsen Kamrani
  • 7,177
  • 5
  • 42
  • 66
0

You can't use nextInt() if you aren't sure that you will have a number coming in. Also, you can't parse e as an integer, because it is not an integer, it's either char or string (I'll suggest string in this case).

That means, your code should look like:

System.out.println("Enter the row number (or enter e to quit the application):");

Scanner rowInput = new Scanner(System.in);
string row1 = rowInput.next();

Then you have the data in a string. You can simply check if the string is e:

if (row1.Equals("e")) ...

It is also a good idea to check if the input is actually an integer then. Good way to check it is described here:

How to check if a String is numeric in Java

Community
  • 1
  • 1
Tomas Pastircak
  • 2,867
  • 16
  • 28
0

Try this:

public class Demo{
    public static void main(String[] args) {
        Scanner s=new Scanner(System.in);
        String choice = null;
        System.out.println("Enter e to exit or some other key to stay:");
        choice=s.next();

        if(choice.equals("e"))
        {
            System.out.println("quits");
            System.exit(0);
        }
        else
        {           
            System.out.println("stays");
        }
    }
}
Lucifer
  • 29,392
  • 25
  • 90
  • 143
0

I have tried several things ....

Attempting to solve this problem by "trying things" is the wrong approach.

The correct approach is to understand what is going on, and then modify your solution to take this into account.

The problem you have is that you have a line of input that could be either a number or the special value e which means quit. (And in fact, it could be a couple of other things too ... but I will come to that.)

When you attempt to either:

  • call Scanner.nextInt() when the next input is not an integer, OR

  • call Integer.parseInt(...) on a String that is not an integer

you will get an exception. So what do you do?

One way is to change what you are doing so that you don't make those calls in those situations. For example:

  • call Scanner.hasInt() to see if the next token is an integer before calling nextInt(), or

  • test for the "e" case before you attempt to convert the String to an integer.

Another way to deal with this is to catch the exception. For example, you could do something like this:

    String s = ...
    try {
        number = Integer.parseInt(s);
    } catch (NumberFormatException ex) {
        if (s.equals("e")) {
            ...
        }
    }

Either way will work, but I'm going to leave you to work out the details.

But the real point I'm trying to make is that the right way to solve this is to understand what is happening in your original version / versions, and based on your understanding, modify what you were doing. If you just randomly "try" alternatives that you found with Google, you won't progress to the point of being a productive programmer.


I said there were other cases. They are:

  • The user types something that is neither a number of your special e character. It could be anything. An empty line, hi mum ...

  • The user types the "end of file" character; e.g. CTRL-D on Linux or CTRL-Z on windows.

If you want your program to be robust you need to deal with these cases too.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
-1

You can't convert a string into integer, use char ASCII codes instead.