gpt4 book ai didi

java - 如何处理InputMismatchException?

转载 作者:行者123 更新时间:2023-12-01 15:33:34 25 4
gpt4 key购买 nike

这是 Bruce Eckel Thinking in Java,第四版的示例

import java.io.BufferedReader;
import java.io.StringReader;
import java.util.Scanner;

public class BetterRead {
public static void main(String[] args) {
BufferedReader input = new BufferedReader(new StringReader("Sir Robin of Camelot\n22 1.61803"));
Scanner stdin = new Scanner(input);
System.out.println("What is your name?");
String name = stdin.nextLine();
System.out.println(name);
System.out.println("How old are you? What is your favorite double?");
System.out.println("(input: <age> <double>)");
int age = stdin.nextInt();
double favorite = stdin.nextDouble();
System.out.println(age);
System.out.println(favorite);
System.out.format("Hi %s.\n", name);
System.out.format("In 5 years you will be %d.\n",
age + 5);
System.out.format("My favorite double is %f.",
favorite / 2);
}
}

这里是输出

 What is your name?
Sir Robin of Camelot
How old are you? What is your favorite double?
(input: <age> <double>)
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextFloat(Scanner.java:2388)
at betterread.BetterRead.main(BetterRead.java:21)
Java Result: 1

我对 Java 还很陌生,但正如您在本例中看到的,int 跟在 buy double 后面。所以它可能工作正常。但仍然抛出InputMismatchException。如何解决这个问题?

最佳答案

问题似乎出在您的区域设置上,因为 1.61803 似乎不是它的有效 double 值。尝试使用 1,61803。

关于java - 如何处理InputMismatchException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9248926/

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