Here is a snippet of my code. When I execute this code I have to hit enter twice
ID: 3558143 • Letter: H
Question
Here is a snippet of my code. When I execute this code I have to hit enter twice in order to get the program to ask the user to Enter a valid amount, when I enter an invalid amount such as -123.45. If you need the whole code just let me know or email me at sluger233@gmail.com
public static BigDecimal ammount() {
BigDecimal money = BigDecimal.ZERO;
boolean exceptionFlag = true;
do {
exceptionFlag = true;
try {
String inputAmount = input.nextLine();
if(inputAmount.indexOf('-') == 0)
{
exceptionFlag = false;
}
else
{
money = new BigDecimal(inputAmount);
int decimalIndex = inputAmount.indexOf('.');
String temp = inputAmount.substring(decimalIndex + 1);
if (decimalIndex != -1)
if (!(temp.length() == 2)) {
exceptionFlag = false;
System.out.print("Enter valid amount (2 digit after decimal): ");
}
}
}
catch (Exception e) {
System.out.print("Enter valid amount: ");
exceptionFlag = false;
}
} while (exceptionFlag == false);
return money;
}
Explanation / Answer
what is happening in your code is, suppose
you enter ' -123.45'
it causes this code to set exceptionFlag == false
if(inputAmount.indexOf('-') == 0)
{
exceptionFlag = false;
}
but it does not catch an exception since the catch part is in else segment, nor does it display the 'Enter valid' error message because of same reason.
However, once you hit enter, the code is still waiting for the user to input a number
try {
String inputAmount = input.nextLine();
...........
it just does not display the 'Enter valid' message.
In order to make your code fine (it is still correct though), you can add the line System.out.print("Enter valid amount: ");
this way --->
if(inputAmount.indexOf('-') == 0)
{
exceptionFlag = false;
System.out.print("Enter valid amount: ");
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.