Question

I was trying to do this:

import java.util.Scanner;
public class Prov{
    public static void main(){
        Scanner getInfo = new Scanner(System.in);
        showInfo(getInfo.next());

    }
    public void showInfo(int numb){
        System.out.println("You typed this integer: " + numb);
    }
        public void showInfo(double numb){
        System.out.println("You typed this double: " + numb);
    }
}

but it doesnt work no matter if I look for scanner.next or scanner.nextInt it wont just get a double when i write a double and an int when I type an int.

Thank You !

Was it helpful?

Solution 2

next() method returns a String not a number, specifically not even an int or double, to fix this, you need to test if the next is a int or is a double. Ie:

if (getInfo.hasNextInt()) {
    showInfo(getInfo.nextInt());
}else if(getInfo.hasNextDouble()) {
    showInfo(getInfo.nextDouble());
}else{
    //Neither int or double
}

Hope this helps!

OTHER TIPS

You can use

if (scanner.hasNextInt()) {
    int i = scanner.nextInt();

} else if(scanner.hasNextDouble()) {
    double d = scanner.nextDouble();

} else {
     scanner.next(); // discard the word

I suggest you read the Javadoc for all the other options it has.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top