poerg
poerg

Reputation: 157

How to use overloaded method (distinguish int or double)

I need to write a program that gets three numbers from the user, then passes those to an overloaded method (I have a double and int).

My question is how do I determine if it's an int or a double?

To get input I'm doing this:

Scanner input = new Scanner( System.in );
double number1 = input.nextDouble(); // read first double
double number2 = input.nextDouble(); // read second double
double number3 = input.nextDouble(); // read third double

MyMathOps MyMathOps = new  MyMathOps();
double result = MyMathOps.maximum( number1, number2, number3 ); 
System.out.println(result);

But what if they enter an int? I want to be able to determine this, and pass it to the int maximum method.

Upvotes: 1

Views: 987

Answers (3)

Paul Bellora
Paul Bellora

Reputation: 55213

Just treat all input as double, since you're supporting floating point inputs. It doesn't make sense to use int only sometimes just because the input happens to be an integer.

Upvotes: 5

Jakub Zaverka
Jakub Zaverka

Reputation: 8874

number1, number2 and number3 are all declared as doubles. Even if they will contain an integer value, they will still be doubles (i.e. value 1.0).

If you want to know it the double value can also be represented as Integer value, you can convert the double to String:

String doubleString = Double.valueOf(number1)

splitting the string around the decimal dot:

String[] split = doubleString.split("\\.");

and then checking the decimal part to contain only zeroes:

boolean canBeInt = split[1].matches("0*");

If it is true, then you can run Integer.parseInt(split[0]) and get integer value (or just cast the original double to int).

Note this solution will not check for maximum integer value.

Upvotes: 1

hungr
hungr

Reputation: 2096

Actually there are several methods to do that. For example you can use input.next() instead of input.nextDouble() and parse the returned String to check the data type (whether it is bounded by Integer's maximum and contains no fractional part)

Upvotes: 1

Related Questions