0

I have a chicken and egg issue of sorts. I'm use to dynamic typing (python) so please be gentle on me if this is a basic thing.

I have a scanner, but I want to allow the user to enter either a string or an integer (1 or 'option1'). Because it's a user input, I don't know the resulting type (int or string). I need to get the user input from the scanner, assign it to a variable, and then pass that variable to an overloaded method.

The problem is that I need to declare the variable type. But, it can be either. How do I handle this?

EDIT

To clarify, I was thinking of doing something like this (Below is pseudo code):

public static float methodname(int choice){
//some logic here
}

public static float methodname(String choice){
//some logic here
}

Scanner input = new Scanner( System.in ); 

choice = input.nextLine();

System.out.println(methodname(choice));

The problem that i'm having is the declaration of 'choice'. What do i put for the type?

3
  • just make it a String and check if it´s only numeric or not afterwards. If it is parse it as an int. Commented Sep 21, 2016 at 13:56
  • how do i check if its numeric if i make it a string? If i make it a string wouldnt it be a string? Commented Sep 21, 2016 at 13:57
  • The String "1" contains only digits so it could be parsed as an int. The string "option1" contains letters so you can't convert it to a string. Commented Sep 21, 2016 at 14:02

2 Answers 2

1

You can take it as a String and try to convert it to an int. If the conversion happens without problems you can use the int version, otherwise use the String version.

String stringValue = ...

try {
    // try to convert stringValue to an int
    int intValue = Integer.parseInt(stringValue);
    // If conversion is possible you can call your method with the int
    call(intValue);
} catch (NumberFormatException e) {
    // If conversion can't happen call using the string
    call(stringValue);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Important to note, but if OP is allowing "option1" or "option 1", you'll need to strip out all characters which are not numbers before trying to parse what remains.
@Jacob yes, I assumed that stringValue is "1", not "option 1". If it is "option 1" the string version is invoked
1

Take the input value as String, convert it to integer using

String number = "1";
int result = Integer.parseInt(number);

if it parses then you can continue using it as a number. And if it fails it will throw NumberFormatException. So you can catch the exception and proceed it with string.

try{ 
    String number = "option1";
    int result = Integer.parseInt(number);
    // proceed with int logic
} catch(NumberFormatException e){
    // handle error and proceed with string logic
}

Comments

Your Answer

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