我很難得到InputMismatchException來捕獲當用戶輸入字符串值而不是int或double。我使用set方法將鍵盤輸入設置爲CompCalc類中的變量,我不確定這是否是問題所在。我嘗試了很多東西,但無濟於事。我可以使用Do/While循環來獲得所需的結果;然而,我是編程新手,並希望在這種情況下成功實現Try/Catch。InputMismatchException不捕獲
這裏是主類:
import java.util.*;
/**
*
* @author shawnwilliams
*/
public class EmpComp {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
CompCalc compensation = new CompCalc();
System.out.println("This program will calculate your total "
+ "compensation for the prior year.");
System.out.println("Enter your total sales: ");
try
{
compensation.setTotalSales(keyboard.nextDouble());
}
catch (InputMismatchException e)
{
System.out.println("Please enter a valid number.");
keyboard.next();
}
System.out.printf("\nYour total compensation for this year is: "
+ "%.2f\n\n ", compensation.getTotalComp());
}
}
這是補償運算類
public class CompCalc {
private final double salary = 50000.00,
commissionRate = 0.02;
private double totalSales,
totalCommission,
totalComp;
public void setTotalSales(double s)
{
totalSales = s;
}
public double getTotalSales()
{
return totalSales;
}
public double getTotalCommission()
{
return totalCommission;
}
public double getSalary()
{
return salary;
}
public double getCommissionRate()
{
return commissionRate;
}
public double getTotalComp()
{
totalComp = totalSales * commissionRate + salary;
return totalComp;
}
}
堆棧跟蹤
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 EmpComp.main(EmpComp.java:33)
提前感謝!
肖恩
問題是,如果你輸入一個無效的響應,它會拋出異常並不再詢問?使用while循環的 – jnd
是正確的方法。你可以在循環中使用try/catch。 – yarivt
正確,儘管有catch語句,但異常仍在拋出。我現在主要在抓捕。我是否正確地假設我將不得不將整個try/catch放到while循環中以提示用戶輸入更新? –