Java 运行时错误输入不匹配程序中的异常



当我运行此代码时,我在代码运行器(一个为功课提交代码的应用程序(中得到此代码

Scanner scan = new Scanner(System.in);
double maxn = -90;
double maxs = 90;
double maxe = 180;
double maxw = -180;
double lat = 0;
double longa = 0;
int x = 1;
while (x != 0) {
System.out.println("Please enter a latitude:");
lat = scan.nextDouble();
if (lat >= maxn && lat <= 90)
maxn = lat;
if (lat <= maxs && lat >= -90)
maxs = lat;
System.out.println("Please enter a longitude:");
longa = scan.nextDouble();
if (longa <= maxe && longa >= -180)
maxe = longa;
if (longa >= maxw && longa <= 180)
maxw = longa;
System.out.println("Would you like to enter another location?");
x = scan.nextInt();
}
System.out.println("Farthest North: " + maxn + "nFarthest South: " + maxs + "nFarthest East: " + maxe + "nFarthest West: " + maxw);

我收到以下错误:

Runtime Error
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at Lesson_20_Activity.main(Main.java:315)
at Ideone.assertRegex(Main.java:85)
at Ideone.assertRegex(Main.java:76)
at Ideone.test(Main.java:40)
at Ideone.main(Main.java:29)

我不知道这个错误是如何工作的,因为我是编码新手。有人可以解释这意味着什么以及如何解决它吗?

编辑:我的输入是

Please enter the latitude: 41.678 Please enter the longitude: 69.938 Would you like to enter another location? 1 Please enter the latitude: 41.755 Please enter the longitude: 69.862 Would you like to enter another location? 1 Please enter the latitude: 41.829 Please enter the longitude: 69.947 Would you like to enter another location? 1 Please enter the latitude: 300 Please enter the longitude: 69.947 Incorrect Latitude or Longitude Please enter the latitude: 41.827 Please enter the longitude: 69.904 Would you like to enter another location? 0 Farthest North: 41.829 Farthest South: 41.678 Farthest East: 69.947 Farthest West: 69.862

另外,我尝试将x更改为双精度和字符串输入,但没有成功。我得到的每個錯誤是NoSuchElementError和NoSuchLineError(分別(

在 Javadoc 中,在以下情况下抛出InputMismatchException

由扫描程序引发,以指示检索到的令牌不 匹配预期类型的模式,或者令牌已超出 预期类型的范围。

在您的代码中,您正在调用scan.nextInt()scan.nextDouble()。请确保仅将有效的int值和double值分别传递给其中每个调用。也就是说,当扫描程序需要整数值(scan.nextInt()(时输入双精度值会抛出上述错误。

请注意,当您不想要换行符时,您应该使用 System.out.print 然后写 '\r'。

我已经运行了您的代码并获得了正确的输出,但您必须注意您向命令行提供了哪些输入。我会读取所有字符串,然后转换为所需的原始格式以避免此错误。

输入经度和纬度后,您将询问重试的问题。

x= nextInt()

在这里,您接受一个 int(0 表示关闭 while 循环,而不是其他(。 如果您在那里键入任何字符串或双精度值,则会导致输入异常。我尝试了您的代码,如果这些整数和小数正确给出,如下所示,它就可以正常工作。

Please enter a latitude:
12.3
Please enter a longitude:
14.3
Would you like to enter another location?
1
Please enter a latitude:
12.3
Please enter a longitude:
14.5
Would you like to enter another location?
0
Farthest North: 12.3
Farthest South: 12.3
Farthest East: 14.3
Farthest West: 14.5

最新更新