检测java中的扫描程序输入(double或int) [英] Detect scanner input in java (double or int)

查看:116
本文介绍了检测java中的扫描程序输入(double或int)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图这样做:

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);
    }
}

但无论我是否寻找扫描仪,它都无法运作.next或scanner.nextInt当我输入一个int时,它只会得到一个double和一个int。

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.

谢谢!

推荐答案

next()方法返回的字符串不是数字,特别是甚至不是int或double,要解决此问题,你需要测试下一个是否一个int或是一个双。即:

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
}

希望这有帮助!

这篇关于检测java中的扫描程序输入(double或int)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆