我的Java程序编译没有任何错误,但不会完全运行

时间:2015-04-05 00:28:03

标签: java

以下是我收到的错误。

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)

以下是我正在使用的代码。我可以输入"姓氏"但后来我收到上面显示的错误信息。任何帮助将不胜感激。

import java.util.*;
public class lab81
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.print("Enter last name:");
double lastName;
lastName = input.nextDouble();
System.out.print("Enter first name:");
double firstName;
firstName = input.nextDouble();
System.out.print("Enter this years units:");
double thisYearsUnits;
thisYearsUnits = input.nextDouble();
System.out.print("Enter last years units:");
double lastYearsUnits;
lastYearsUnits = input.nextDouble();
double numberOfUnits = thisYearsUnits;
final double UNITS1 = 1000;
final double UNITS2 = 3000;
final double UNITS3 = 6000;
final double BONUS1 = 25;
final double BONUS2 = 50;
final double BONUS3 = 100;
final double BONUS4 = 200;
if(thisYearsUnits < lastYearsUnits)
{
   double bonusAmount;
   bonusAmount = 0;
   System.out.println(lastName + ", " + firstName);
   System.out.println("Bonus is $" + bonusAmount);
}
else if(numberOfUnits <= UNITS1)
{
   double bonusAmount;
   bonusAmount = BONUS1;
   System.out.println(lastName + ", " + firstName);
   System.out.println("Bonus is $" + bonusAmount);
}
else if(numberOfUnits <= UNITS2)
{
   double bonusAmount;
   bonusAmount = BONUS2;
   System.out.println(lastName + ", " + firstName);
   System.out.println("Bonus is $" + bonusAmount);
}
else if(numberOfUnits <= UNITS3)
{
   double bonusAmount;
   bonusAmount = BONUS3;
   System.out.println(lastName + ", " + firstName);
   System.out.println("Bonus is $" + bonusAmount);
}
else if(numberOfUnits > UNITS3)
{
   double bonusAmount;
   bonusAmount = BONUS4;
   System.out.println(lastName + ", " + firstName);
   System.out.println("Bonus is $" + bonusAmount);
}
}
} 

3 个答案:

答案 0 :(得分:0)

您正在尝试将字符解析为双精度,这就是它抛出异常的原因。

声明你的名字&amp;姓氏为字符串,使用

从输入中获取
Input.nextLine()

而不是

Input.nextDouble()

答案 1 :(得分:0)

您是否将文本存储到firstname和lastname变量中?这是明显的数据类型不匹配。使用字符串,它们是存储文本的内容。

String firstname;
// Stuff
firstname = input.nextLine();

双倍是指一定长度的浮点数。另外,尽可能使用int。

final int UNITS1 = 1000;
final int UNITS2 = 3000;
final int UNITS3 = 6000;
final int BONUS1 = 25;
final int BONUS2 = 50;
final int BONUS3 = 100;
final int BONUS4 = 200;
// Stuff
int bonusAmount;

处理您的原始数据类型知识。希望这有帮助!

答案 2 :(得分:0)

抛出这些异常的情况: -

InputMismatchException - 如果下一个标记与Float正则表达式不匹配,或者超出范围

lastname=scaner.nextDouble();

在这一行你会输入字符串值,但它预计会加倍。

NoSuchElementException - 如果输入已用尽

IllegalStateException - 如果此扫描程序已关闭