Aditya
Aditya

Reputation: 1135

How to enter constants as an input in Java

I have been programming in Java and I was using the constant Integer.MAX_VALUE in my calculations in solving programming problems.

I was wondering if there was a way for Java to interpret Integer.MAX_VALUE or Integer.MIN_VALUE (system defined constants) when entered as input by the user without doing the obvious string comparisons.

Currently I am using the constants as:

int MAXIMUMINTEGER = Integer.MAX_VALUE;
int MINIMUMINTEGER = Integer.MIN_VALUE;

I would want to use them as follows:

System.out.println("Enter a number : ");
int number = in.nextInt();
System.out.println("The number entered is : " + number);

In the output console:

Enter a number: Integer.MAX_INT
The number entered is : 2147483647

I am looking at ways to make java understand defined constants as user input.

Any help on this is appreciated.

Upvotes: 2

Views: 762

Answers (1)

Kelevandos
Kelevandos

Reputation: 7082

This is not easily possible unless the values are explicitly stated in your code (so the String comparison you mentioned).

However, there could be a hardcore solution using reflection mechanism, which is basically meta-access to classes and their fields. Still, you would need to parse the input as a field name, like this:

System.out.println("Enter a number : ");
String input = in.nextString();
Class klass = Class.forName("java.lang." + input.split("\\.")[0]);
Field field = klass.getField(input.split("\\.")[1]);
int number = field.getInt(klass);
System.out.println("The number entered is : " + number);

This would get the expected result for your input (provided you pass Integer.MAX_VALUE and not Integer.MAX_INT, as the latter is not a constant value).

I guess you could turn it into functioning code using Integer.valueOf() first and then parsing the String if the value is invalid.

Still, there are so many border cases that this would hardly be worth it in any imaginable scenario :-)

Upvotes: 5

Related Questions