0

I have to read options of menu from console and the options can be integer or string. my question is if there is another way to check of the input is string or int

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class Read { 


    public Object read(){
        String option = null;
        BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));
        try {
            option = buffer.readLine();
            if(isInt(option)){
                return Integer.parseInt(option);
            } else if(isString(option)){
                return option;
            }
        } catch (IOException e) {
            System.out.println("IOException " +e.getMessage());
        }
        return null;
    }


    private boolean isString(String input){
        int choice = Integer.parseInt(input);
        if(choice >= 0){
            return false;
        }
        return true;
    }

    private boolean isInt(String input){
        int choice = Integer.parseInt(input);
        if(choice >= 0){
            return true;
        }
        return false;
    }

}

3 Answers 3

3

Something like this?

boolean b = true:
try 
{ 
     int a = Integer.parseInt(input); 
} 
catch(NumberFormatException ex) 
{ 
      b = false;
}

If it's an not integer b will be false or else remains true

Sign up to request clarification or add additional context in comments.

2 Comments

@Bohemian Yeah it saves wrapping and unwrapping
Not just that - it means it can't be null; there are only two possible values of a boolean, but a Boolean has three.
1

It depends what you mean by "integer".

If you mean "a whole number", the simplest and best way is use regex:

private boolean isInt(String input){
    return input.matches("\\d+");
}

If you mean "a java int", then you must attempt to parse it and treat an exception as proof it is not a valid int:

private boolean isInt(String input){
    try {
        Integer.parseInt(input);
        return true;
    } catch (NumberFormatException ignore) {
        return false;
    }
}

Comments

0

You could use regex, then the method looks like this:

private boolean isInt(String input){
    return input.matches("\\d+");
}

Then the check it:

        if (isInt(option)){
            return Integer.parseInt(option);
        } else {
            return option;
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.