We read your photo as:
Write a Java program that calculates and displays the balance of an investment over several years, using a do-while loop. The program should prompt the user for the initial investment amount.
Computer Science
ScanSolve AI Answer
Step-by-step solution
5 stepsimport javax.swing.JOptionPane;
public class BankBalanceDoWhile {
public static void main(String[] args) {
double investmentAmount = 0.0;
double annualInterestRate = 0.05; // Assuming a fixed annual interest rate of 5%
int year = 0;
int choice = 0;
boolean validInput;
// Step 1: Get the initial investment amount
do {
String input = JOptionPane.showInputDialog("Enter your initial investment amount:");
try {
investmentAmount = Double.parseDouble(input);
if (investmentAmount < 0) {
JOptionPane.showMessageDialog(null, "Investment amount cannot be negative. Please enter a positive value.");
validInput = false;
} else {
validInput = true;
}
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Invalid input. Please enter a numeric value for the investment amount.");
validInput = false;
}
} while (!validInput);
double currentBalance = investmentAmount;
// Step 2: Loop to display annual balances using a do-while loop
do {
year++;
currentBalance *= (1 + annualInterestRate); // Calculate balance for the current year
// Display the balance for the current year
JOptionPane.showMessageDialog(null, String.format("Balance after year %d: R%.2f", year, currentBalance));
// Ask the user if they wish to see the balance for another year
do {
String choiceInput = JOptionPane.showInputDialog(
"Do you wish to see the balance for another year?\n" +
"Enter 1 to view the next balance.\n" +
"Enter 0 to exit."
);
try {
choice = Integer.parseInt(choiceInput);
if (choice == 1 || choice == 0) {
validInput = true;
} else {
JOptionPane.showMessageDialog(null, "Invalid input. You entered " + choice + ". Please enter 1 to continue or 0 to exit.");
validInput = false;
}
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Invalid input. Please enter an integer (1 or 0).");
validInput = false;
}
} while (!validInput);
} while (choice == 1);
JOptionPane.showMessageDialog(null, "Thank you for using the Bank Balance Calculator.");
}
}
Explanation:
Initialize variables.
investmentAmount: Stores the initial amount invested.annualInterestRate: Set to0.05(5%) as a common example, though the problem doesn't specify.year: Tracks the number of years passed.choice: Stores the user's input to continue or exit.validInput: A boolean flag to manage input validation loops.
Get initial investment amount.
- A
do-whileloop is used to repeatedly prompt the user for the initial investment amount until a valid positive numeric input is provided. JOptionPane.showInputDialogis used for input.Double.parseDouble()attempts to convert the input string to a double.- A
try-catchblock handlesNumberFormatExceptionif the input is not a valid number. - An additional check ensures the investment amount is not negative.
- A
Calculate and display annual balances.
- The main logic is encapsulated in another
do-whileloop, which continues as long as the user enters1. - Inside the loop,
yearis incremented, andcurrentBalanceis updated by multiplying it with(1 + annualInterestRate). JOptionPane.showMessageDialogdisplays the balance for the current year, formatted to two decimal places.
- The main logic is encapsulated in another
Prompt user for continuation and validate input.
- After displaying each year's balance, an inner
do-whileloop prompts the user to enter1to view the next balance or0to exit. - This inner loop ensures that only
1or0are accepted. Any other integer input triggers an error message, and the user is prompted again without terminating the program. Integer.parseInt()converts the user's choice input.- A
try-catchblock handlesNumberFormatExceptionfor non-integer inputs.
- After displaying each year's balance, an inner
Exit message.
- Once the user enters
0, the maindo-whileloop terminates, and a final thank you message is displayed.
This program exclusively uses the
do-whileloop structure andmain()method as requested.- Once the user enters
Was this helpful?
Still stuck on this one?
Ask a follow-up, and the answer starts from this question.
Got a different question?Ask your own question
More Computer Science Questions
QWhat is the name of the application program displayed in Figure 1? Write a formula to find the…QCalculate the total initial investment.QCalculate the future value of an investment using simple interest and compound interest (annually…QCalculate the principal amount invested given simple interest earned, time period, and annual…QCalculate simple interest for 1 year and total amount after 2 years, and compound interest for 2…