Search code examples
javaintegerdoublejava.util.scannerdetect

Detect scanner input in java (double or int)


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 !


Solution

  • 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!