我的扫描器类java代码有一个异常,这是一个错误
我在运行代码时遇到此错误,请帮助
Exception in thread "main" java.util.InputMismatchException
如果您能对代码进行全面的修复,我将不胜感激
在这种情况下,当我输入像重量这样的数据时,它充满了错误,而且很烦人
package howto;
import java.util.Scanner;
public class Howto {
public static void main(String[] args) {
Scanner sc1 = new Scanner(System.in);
Scanner sc2 = new Scanner(System.in);
double weightkg [] = new double [30];
double weightkgEndOfMonth [] = new double [30];
String name [] = new String [30];
double weightDifference [] = new double[30];
for (int i = 0; i<31; i++)
{
System.out.println("Input name: ");
String scanner1 = sc1.nextLine();
name [i] = scanner1;
System.out.println("Input weight: ");
double scanner2 = sc2.nextDouble();
if(!sc1.hasNextDouble())
{
System.out.println("Invalid Weight!. Start Again");
} else
{
weightkg[i] = scanner2;
}
System.out.println("Name: " + name[i]);
System.out.println("weight : " + weightkg[i]);
}
for (int i = 0; i<31; i++)
{
System.out.println("Input weight at the end of month: ");
double scanner2 = sc2.nextDouble();
if(!sc1.hasNextDouble())
{
System.out.println("Invalid Weight!. Start Again");
} else
{
weightkgEndOfMonth[i] = scanner2;
}
weightDifference [i] = weightkg[i] - weightkgEndOfMonth[i];
if(weightDifference[i]>2.5)
{
System.out.println("Student with a weight difference greater than 2.5kg: " + name[i]);
System.out.println("Weight difference: " + weightDifference[i]);
System.out.println("Rise");
}
if(weightDifference[i]> -2.5)
{
System.out.println("Student with a weight difference greater than 2.5kg: " + name[i]);
System.out.println("Weight difference: " + weightDifference[i]);
System.out.println("Fall");
}
}
}
}
错误消息:
run:
Input name:
Test
Input weight:
90
10
Name: Test
weight : 90.0
Input name:
Input weight:
Test1
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.nextDouble(Scanner.java:2413)
at howto.Howto.main(Howto.java:45)
Java Result: 1
BUILD SUCCESSFUL (total time: 16 seconds)
# 1 楼答案
你的代码中有一些逻辑错误。每一行我都提到他们
现在它运行良好
# 2 楼答案
有几个问题很突出
首先
你不需要多个扫描仪,反正它们都是从同一个流中读取的,最好只使用一个,减少复杂性
接下来
当使用
nextDouble
时,缓冲区仍然包含一个换行标记,这意味着下次使用nextLine
时,它将返回一个空白String
并继续另外,
hasNextDouble
似乎在等待数据,但您已经从缓冲区读取了double
值,留下了悬而未决的新行。在我的测试中,这导致程序在等待更多输入时出现问题我通过这样做“解决”了基本问题
现在这个“会”起作用,但它不是最好的解决方案。另一种“不同”的方法可能是将权重读入为
String
,并尝试将其解析为double
,这使您有机会捕获无效输入,并以更合适的方式处理它,例如}