如何找出哪个变量抛出异常? [英] How to find out which variable is throwing an exception?

查看:126
本文介绍了如何找出哪个变量抛出异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在撰写一个程序,根据账单和小费率计算小费和总额。

I'm writing a program that culculates tip and total from bill and tip rate.

public void takeUserInput() {
    Scanner sc = new Scanner(System.in);    
    double billAmount;
    int tipRate;

    try {
        System.out.print("What is the bill? ");
        billAmount = sc.nextDouble();
        System.out.print("What is the tip percentage? ");
        tipRate = sc.nextInt();

        tc.calculate(billAmount, tipRate);
    } catch (InputMismatchException e1) {
        String errorMessage = "Please enter a valid number for the ";
        // errorMessage += billAmount or
        // errorMessage += tipRate ?
    }

我正在寻找一种方法来找出抛出InputMismatchException的变量,所以我可以将哪个变量名称添加到变量errorMessage中并打印到屏幕上。

I'm looking for a way to find out which variable throws InputMismatchException, so I can add which variable name into variable errorMessage and print to the screen.

推荐答案

变量没有抛出异常,评估变量赋值的右侧是,因此在异常中没有信息说明它要分配哪个变量使其成功。

The variable isn't throwing the exception, the evaluation of the right hand side of the variable assignment is, and so there is no information in the exception to say which variable it was about to assign that to had it succeeded.

您可以考虑的是一种包含提示消息和重试的新方法:

What you could consider instead is a new method that encompasses the prompting messages and retries:

billAmount = doubleFromUser(sc, "What is the bill? ", "bill");

其中 doubleFromUser 是:

static double doubleFromUser(Scanner sc, String prompt, String description){
    while(true) { //until there is a successful input
        try {
            System.out.print(prompt); //move to before the loop if you do not want this repeated
            return sc.nextDouble();
        } catch (InputMismatchException e1) {
            System.out.println("Please enter a valid number for the " + description);
        }
    }
}

你需要一个不同的对于int和double,但如果你有更多的提示,你将保存为长期。

You will need a different one for int and double, but if you have more prompts, you will save in the long run.

这篇关于如何找出哪个变量抛出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆