I have a program here that accepts a numeric value (stored as a BigDecimal
) and the currency (USD or CNY) stored as a String
. With the help of user dimo414, I was able to account for blank inputs and non-numeric inputs, while also allowing the user to retry until a valid input is read.
Here is the code:
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);
}
Now I'm having trouble dealing with when moneyInput
is valid, but currency
is not, e.g. 100.00 abc
. In this case, I'd like to prompt the user to re-enter a value for currency
while retaining the value of money
.
I tried using a similar do-while loop around the section that prompted for currency
and continued onto the if-else block like so:
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);
But this solution was ineffective because it would display the exception error message from the outer catch
block, so I'd actually have to implement a do-while loop inside a try-catch block inside a try-catch block, and that got messy really fast.
I also tried defining a new function outside of main
called readCurrency
that I could invoke in the else
block, but I ran into issues of variable scopes. I am still a beginner in Java so I didn't know how to properly define a function and pass the necessary info to it.
What other ways are there to loop back up to the top of that try block and allow the user to re-enter the currency only?
Thanks so much for reading and providing feedback.