Status
Not open for further replies.
can you please explain this java program in a very detailed way via comments very detailed

import java.util.InputMismatchException;
import java.util.Scanner;

public class InflationRateCalculator {
static String[] usernames = new String[10];
static String[] passwords = new String[10];
static int userCount = 0;
static boolean loggedIn = false;
static String product = "";
static String currentUser = "";

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int previousYear = 0;
int currentYear = 0;

while (true) {
if (!loggedIn) {
System.out.println("Welcome to Inflation Rate for Goods and Services Calculator\n");
System.out.println("Please choose an option:\n");
System.out.println("1. Log in");
System.out.println("2. Create account");
System.out.println("3. Exit\n\n");
int choice = scanner.nextInt();

switch (choice) {
case 1:
System.out.println("\nEnter username:");
String username = scanner.next();
System.out.println("\nEnter password:");
String password = scanner.next();
if (login(username, password)) {
System.out.println("\nLogin successful.");
loggedIn = true;
currentUser = username;
} else {
System.out.println("Invalid username or password. Please try again.\n");
}
break;
case 2:
System.out.println("\nEnter username:");
String newUsername = scanner.next();
System.out.println("\nEnter password:");
String newPassword = scanner.next();
if (createAccount(newUsername, newPassword)) {
System.out.println("\n\nAccount created successfully.\n");
} else {
System.out.println("\nUsername already exists. Please choose a different username.\n");
}
break;
case 3:
System.out.println("\n\nExiting program...\n");
scanner.close();
System.exit(0);
default:
System.out.println("\nInvalid choice. Please try again.\n");
break;
}
} else {
System.out.println("\nWelcome, " + currentUser + "!");
System.out.println("\nPlease choose an option:");
System.out.println("\n1. Calculate inflation rate");
System.out.println("\n2. Logout");
int choice = scanner.nextInt();

switch (choice) {
case 1:
boolean validInput = false;
while (!validInput) {
try {

System.out.println("\nEnter product name :");
product = scanner.next();

System.out.println("\nEnter previous year:");
previousYear = scanner.nextInt();
System.out.println("\nEnter current year:");
currentYear = scanner.nextInt();
System.out.println("\nEnter current price:");
double cpi = scanner.nextDouble();
System.out.println("\nEnter previous price:");
double previousCpi = scanner.nextDouble();
double inflationRate = (int) Math.round(cpi - previousCpi) / previousCpi * 100;
System.out.println("\nInflation rate for " + previousYear + "-" + currentYear + " (" + product + ") = " + inflationRate + "%");

validInput = true;
} catch (InputMismatchException e) {
System.out.println("\nYou entered a non-integer. Please enter integers only.");
scanner.next();
}
}
break;
case 2:
System.out.println("\n\nLogging out...\n\n");
loggedIn = false;
currentUser = "";
break;
default:
System.out.println("\nInvalid choice. Please try again.");
break;


}
}
}
}

public static boolean login(String username, String password) {
for (int i = 0; i < userCount; i++) {
if (usernames.equals(username) && passwords.equals(password)) {
return true;
}
}
return false;
}

public static boolean createAccount(String username, String password) {
for (int i = 0; i < userCount; i++) {
if (usernames.equals(username)) {
return false;
}
}
usernames[userCount] = username;
passwords[userCount] = password;
userCount++;
return true;
}
}
 
This is a Java program that simulates an inflation rate calculator for goods and services. It allows users to log in, create new accounts, and calculate inflation rates for a specified product between two years.

Let's go through each section of the program in detail:

1. Variable Declarations:
Code:
static String[] usernames = new String[10];
static String[] passwords = new String[10];
static int userCount = 0;
static boolean loggedIn = false;
static String product = "";
static String currentUser = "";
This section declares several static variables that are available throughout the program. These variables are:
  • usernames: an array of strings that stores usernames for registered users.
  • passwords: an array of strings that stores passwords for registered users.
  • userCount: an integer that keeps track of how many users have been registered.
  • loggedIn: a boolean that indicates whether or not a user is currently logged in.
  • product: a string that stores the name of the product for which the inflation rate is being calculated.
  • currentUser: a string that stores the username of the user who is currently logged in.

2. Main Method:
Code:
public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int previousYear = 0;
    int currentYear = 0;
    // code continues...
The main method initializes a Scanner object, and two integer variables previousYear and currentYear to store the years for which the inflation rate is being calculated. It then enters an infinite loop using while (true).

3. Login/Account Creation:
Code:
while (true) {
    if (!loggedIn) {
        System.out.println("Welcome to Inflation Rate for Goods and Services Calculator\n");
        System.out.println("Please choose an option:\n");
        System.out.println("1. Log in");
        System.out.println("2. Create account");
        System.out.println("3. Exit\n\n");
        int choice = scanner.nextInt();
        // code continues...
Within the infinite loop, the program first checks if the user is logged in or not. If the user is not logged in, the program presents the user with a menu of options, and prompts the user to enter a choice using scanner.nextInt(). The different options are:
  • Option 1: Log in
  • Option 2: Create account
  • Option 3: Exit

Depending on the user's choice, the program either logs the user in, creates a new account, or exits the program.

4. Logging in:
Code:
case 1:
    System.out.println("\nEnter username:");
    String username = scanner.next();
    System.out.println("\nEnter password:");
    String password = scanner.next();
    if (login(username, password)) {
        System.out.println("\nLogin successful.");
        loggedIn = true;
        currentUser = username;
    } else {
        System.out.println("Invalid username or password. Please try again.\n");
    }
    break;
If the user chooses option 1 to log in, the program prompts the user to enter their username and password. It then calls the login method to check if the username and password are valid. If they are, the user is logged in and the program sets loggedIn to true and currentUser to the current user's username.

5. Creating an Account:
Code:
case 2:
    System.out.println("\nEnter username:");
    String newUsername = scanner.next();
    System.out.println("\nEnter password:");
    String newPassword = scanner.next();
    if (createAccount(newUsername, newPassword)) {
        System.out.println("\n\nAccount created successfully.\n");
    } else {
        System.out.println("\nUsername already exists. Please choose a different username.\n");
    }
    break;
If the user chooses option 2 to create an account, the program prompts the user to enter a new username and password. It then calls the createAccount method to create a new account. If the account is created successfully, the program prints a success message. If the username already exists, the program prints an error message.

6. Exiting the Program:
Code:
case 3:
    System.out.println("\n\nExiting program...\n");
    scanner.close();
    System.exit(0);
If the user chooses option 3 to exit the program, the program prints a message and exits using System.exit(0).

7. Calculating Inflation Rate:
Code:
} else {
    System.out.println("\nWelcome, " + currentUser + "!");
    System.out.println("\nPlease choose an option:");
    System.out.println("\n1. Calculate inflation rate");
    System.out.println("\n2. Logout");
    int choice = scanner.nextInt();
    // code continues...
If a user is logged in, the program presents the user with a menu of options, and prompts the user to enter a choice using scanner.nextInt(). The different options are:
  • Option 1: Calculate inflation rate
  • Option 2: Logout

Depending on the user's choice, the program either calculates the inflation rate for a specified product between two years, or logs the user out.

8. Calculating Inflation Rate (Continued):
Code:
case 1:
    boolean validInput = false;
    while (!validInput) {
        try {
            System.out.println("\nEnter product name :");
            product = scanner.next();
            System.out.println("\nEnter previous year:");
            previousYear = scanner.nextInt();
            System.out.println("\nEnter current year:");
            currentYear = scanner.nextInt();
            System.out.println("\nEnter current price:");
            double cpi = scanner.nextDouble();
            System.out.println("\nEnter previous price:");
            double previousCpi = scanner.nextDouble();
            double inflationRate = (int) Math.round(cpi - previousCpi) / previousCpi * 100;
            System.out.println("\nInflation rate for " + previousYear + "-" + currentYear + " (" + product + ") = " + inflationRate + "%");
            validInput = true;
        } catch (InputMismatchException e) {
            System.out.println("\nYou entered a non-integer. Please enter integers only.");
            scanner.next();
        }
    }
    break;
If the user chooses option 1 to calculate the inflation rate, the program prompts the user to enter the product name, previous year, current year, current price, and previous price. It then calculates the inflation rate using the formula (current price - previous price) / previous price * 100, and prints the result to the console.

If the user enters a non-integer value, the program catches the InputMismatchException thrown by scanner.nextDouble(), prints an error message, and prompts the user to enter integers only.

9. Logging Out:
Code:
case 2:
    System.out.println("\n\nLogging out...\n\n");
    loggedIn = false;
    currentUser = "";
    break;
If the user chooses option 2 to log out, the program sets loggedIn to false and currentUser to an empty string.

10. Login and Account Creation Methods:
Code:
public static boolean login(String username, String password) {
    for (int i = 0; i < userCount; i++) {
        if (usernames[i].equals(username) && passwords[i].equals(password)) {
            return true;
        }
    }
    return false;
}

public static boolean createAccount(String username, String password) {
    for (int i = 0; i < userCount; i++) {
        if (usernames[i].equals(username)) {
            return false;
        }
    }
    usernames[userCount] = username;
    passwords[userCount] = password;
    userCount++;
    return true;
}
These methods are used to check if a user's login credentials are valid (login), or to create a new account (createAccount).

  • login checks if the username and password are stored in the usernames and passwords arrays. If they are, it returns true. Otherwise, it returns false.
  • createAccount checks if the username already exists in the usernames array. If it does, it returns false. Otherwise, it stores the new username and password in the usernames and passwords arrays, and increments userCount. It then returns true.
 
Status
Not open for further replies.

Similar threads

Back
Top