0

我试图这样做:

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

但无论我查找scanner.next 还是scanner.nextInt 它都不起作用,当我写一个double 时它不会只得到一个double,而当我输入一个int 时它不会得到一个int。

谢谢你 !

4

2 回答 2

3

您可以使用

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

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

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

我建议您阅读 Javadoc 以了解它具有的所有其他选项。

于 2013-10-19T20:13:36.030 回答
1

next() 方法返回一个字符串而不是数字,特别是甚至不是 int 或 double,要解决此问题,您需要测试 next 是 int 还是 double。IE:

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

希望这可以帮助!

于 2013-10-19T20:16:33.903 回答