【发布时间】:2016-07-20 09:55:59
【问题描述】:
我这里有一个程序,它接受一个数值(存储为BigDecimal)和存储为String 的货币(美元或人民币)。在用户 dimo414 的帮助下,我能够解释空白输入和非数字输入,同时还允许用户重试直到读取到有效输入。
代码如下:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the amount of money and specify"
+ " currency (USD or CNY): ");
Boolean invalidInput; // breaks out of do-while loop after successful outcome
do {
invalidInput = false;
try {
String line = input.nextLine();
Scanner lineScan = new Scanner(line);
BigDecimal moneyInput = lineScan.nextBigDecimal();
String currency = lineScan.next();
if (currency.equals("USD")) {
// convert USD to CNY
} else if (currency.equals("CNY")) {
// convert CNY to USD
} else {
/*
reprompt user for currency,
but retain the value of moneyInput;
repeat process until valid currency
*/
}
} catch (NoSuchElementException | IllegalStateException e) {
// deals with errors:
// non-numeric moneyInput or blank input
}
} while (invalidInput);
}
现在我在处理 moneyInput 有效但 currency 无效时遇到问题,例如100.00 abc。在这种情况下,我想提示用户重新输入currency 的值同时保留 money 的值。
我尝试在提示 currency 的部分周围使用类似的 do-while 循环,然后继续进入 if-else 块,如下所示:
do {
String currency = lineScan.next();
if (currency.equals("USD")) {
// convert USD to CNY
} else if (currency.equals("CNY")) {
// convert CNY to USD
} else {
invalidInput = true;
System.out.print("Please enter a valid currency: ");
// since invalidInput == true,
// jump back up to the top of the do block
// reprompt for currency
}
} while (invalidInput);
但是这个解决方案是无效的,因为它会显示来自外部 catch 块的异常错误消息,所以我实际上必须在 try-catch 块内的 try-catch 块内实现一个 do-while 循环,很快就变得一团糟。
我还尝试在 main 之外定义一个名为 readCurrency 的新函数,我可以在 else 块中调用它,但我遇到了变量范围的问题。我仍然是 Java 初学者,所以我不知道如何正确定义函数并将必要的信息传递给它。
还有哪些其他方法可以循环回到该 try 块的顶部并允许用户仅重新输入货币?
非常感谢您阅读并提供反馈。
【问题讨论】:
-
你不能分两步要求输入吗: - 插入金额 //处理金额 - 插入货币 //处理它 每个“交易”将是不同的方法,这可以要求重新输入输入或任何需要的内容
-
如果用户第一次插入
100.00 abc,程序会问用户什么? -
@nickzoum 显示来自
catch块的错误消息,然后是我暂时放置在else块中的打印消息。然后用户可以重新输入。这是一个截图以防万一(imgur.com/a/Z2PRc)。请注意,对于重新输入,程序需要money和currency才能继续。 -
@SCouto 由于处理
moneyInput的部分在 do-while 循环内,moneyInput在do块内有一个范围,所以我无法单独处理currency -
我会写一个答案
标签: java loops try-catch do-while