Detect scanner input in java (double or int)

最后都变了- 提交于 2019-12-11 20:09:31

问题


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 !


回答1:


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!




回答2:


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.



来源:https://stackoverflow.com/questions/19470591/detect-scanner-input-in-java-double-or-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!