Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining input for Overloaded Method

I'm running into a bit of an issue with determining if the user input is an int or double.

Here's a sample:

public static int Square(int x)
{
    return x*x;
}

public static double Square(double x)
{
    return x*x;
}

I need to figure out how to determine based on the Scanner if the input is a int or double for the above methods. However since this is my first programming class, I'm not allowed to use anything that hasn't been taught - which in this case, has been the basics.

Is there anyway of possibly taking the input as a String and checking to see if there is a '.' involved and then storing that into an int or double?

Lastly, I'm not asking for you to program it out, but rather help me think of a way of getting a solution. Any help is appreciated :)

like image 868
Miranda Avatar asked Jan 17 '26 01:01

Miranda


1 Answers

The Scanner has a bunch of methods like hasNextInt, hasNextDouble, etc. which tell you whether the "next token read by the Scanner can be interpreted as a (whatever)".

like image 133
Karl Knechtel Avatar answered Jan 19 '26 14:01

Karl Knechtel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!