从扫描器输入接收浮点数 Java

Receiving float from Scanner input Java

我需要一个方法来检查用户的输入是否是浮点数,如果是字符串或整数则应该抛出异常。

我在方法外声明扫描仪:

    Scanner sc = new Scanner(System.in);

方法定义为:

private boolean CheckFloat(Scanner sc) throws MyException {
    if(!sc.hasNextFloat()){
        throw new MyException("Wrong type");
    }
    else {
        float input = sc.nextFloat();
        if(input%1==0) {
            throw new MyException("Wrong type");
        }
        else return true;
    }
}

问题是无论用户输入什么都会抛出异常,所以我的问题是:我到底做错了什么?

我知道在 Java 中,像 1.2 这样的输入被解释为双精度,但是如何从控制台获取浮点数呢?还是我误解了 hasNextFloat() 方法或整个 Scanner 的工作原理?

到目前为止我还没有发现任何有用的东西

由于您使用的是 nextFloat(),因此您必须确保输入的是浮点数,否则请使用 next()

清除扫描仪
public static void main(String[] args) throws Exception {
    while (true) {
        System.out.print("Enter a float: ");
        try {
            float myFloat = input.nextFloat();
            if (myFloat % 1 == 0) {
                throw new Exception("Wrong type");
            }
            System.out.println(myFloat);
        } catch (InputMismatchException ime) {
            System.out.println(ime.toString());
            input.next(); // Flush the buffer from all data
        }
    }
}

结果:

更新

您仍然需要处理 InputMismatchException,只需在 catch 块中抛出您自己的异常即可。

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    // while (true) just for testing
    while (true) {
        try {
            System.out.print("Enter a float: ");
            System.out.println(CheckFloat(input));
        } catch (MyException me) {
            System.out.println(me.toString());
        }
    }
}

private static float CheckFloat(Scanner sc) throws MyException {
    try {
        float input = sc.nextFloat();
        if (input % 1 == 0) {
            throw new MyException("Wrong type");
        } else {
            return input;
        }
    } catch (InputMismatchException ime) {
        sc.next(); // Flush the scanner

        // Rethrow your own exception
        throw new MyException("Wrong type");
    }
}

private static class MyException extends Exception {
    // You exception details
    public MyException(String message) {
        super(message);
    }
}

结果: