InputMismatchException未捕获

时间:2015-05-18 03:45:39

标签: java

当用户输入字符串值而不是int或double时,我很难获取InputMismatchException。我使用set方法将键盘输入设置为CompCalc类中的变量,我不确定这是否是问题所在。我尝试过很多东西,但无济于事。我可以使用Do / While循环来实现所需的结果;但是,我是编程新手,并希望在这种情况下成功实现Try / Catch。

这是主要课程:

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)

提前致谢!

肖恩

2 个答案:

答案 0 :(得分:0)

这应该对你有用。

boolean ok = false;
while(!ok) {
    try {
        compensation.setTotalSales(keyboard.nextDouble());
        ok = true;
    }
    catch (InputMismatchException e) {
        System.out.println("Please enter a valid number.");
        keyboard.next();
    }
}

答案 1 :(得分:0)

我发现了问题所在。问题不在我写的代码中,而是在我编写Netbeans代码的方式。我需要使用IDE来完成这项任务,我对Netbeans如何编译文件和构建项目并不熟悉。当我在命令行中编译主类文件并且一切按预期工作时,我认识到了这一点。我浪费时间试图找出一个不存在的问题。

感谢您的时间@yarivt!