gpt4 book ai didi

java - 通过 Scanner.nextFloat() 读取 float 时出现 InputMismatchException

转载 作者:太空宇宙 更新时间:2023-11-04 09:06:58 29 4
gpt4 key购买 nike

当我使用带有整数值的程序时,它可以工作,但是当我输入浮点值(例如 47.3)时,它不能工作。您能帮我定义问题吗?

代码:

package ex1;
import java.util.Scanner;

public class test {

static Scanner input = new Scanner(System.in);

public static void main (String[] args) {

float n;

System.out.println("enter a number:");

n = input.nextFloat();

if (n > 0 && n % 2 == 0) {
System.out.println("the number is positive and even");
}
else if (n > 0 && n % 2 != 0) {
System.out.println("the number is positive and odd");
}
else if (n < 0 && n % 2 == 0) {
System.out.println("the number is negative and even");
}
else if (n < 0 && n % 2 != 0) {
System.out.println("the number is negative and odd");
}
else if (n == 0) {
System.out.println("the number is zero");
}

}
}

问题:

Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextFloat(Scanner.java:2496)
at ex1.test.main(test.java:14)

谢谢

最佳答案

在 Java 中,逗号被视为小数点分隔符。因此,要使用浮点输入,您应该替换“.”通过“,”

关于java - 通过 Scanner.nextFloat() 读取 float 时出现 InputMismatchException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60120649/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com