Lab 5B (Solved)

Unit 5

Posted on 4/21/2025

Question 1

import java.util.Scanner;
import java.text.DecimalFormat;

public class BDToEuroConverter {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        final double conversionRate = 1.85;

        // Format to show up to 2 decimal places, without trailing zeroes
        DecimalFormat df = new DecimalFormat("0.##");

        System.out.println("BD to EUR converter");

        while (true) {
            System.out.println("Please enter amount (-99 to quit): ");

            if (scanner.hasNextDouble()) {
                double bdAmount = scanner.nextDouble();

                if (bdAmount == -99) {
                    break;
                }

                double euroAmount = bdAmount * conversionRate;

                System.out.println(df.format(bdAmount) + "BD is equal to " + df.format(euroAmount) + "Euros");
            } else {
                System.out.println("Invalid input. Please enter a number.");
                scanner.next(); // clear invalid input
            }
        }

        scanner.close();
    }
}

Question 2

// This method starts the program and provides the menu
public static void convert() {
    Scanner input = new Scanner(System.in);
    DecimalFormat df = new DecimalFormat("#.#");
    df.setMinimumFractionDigits(1);
    df.setMaximumFractionDigits(2);
    double amount;
    
    System.out.println("BD to EUR converter");
    do {
        System.out.print("Please enter amount (-99 to quit): \n");
        amount = input.nextDouble();
        
        if (amount != -99) {
            String bdAmount = amount % 1 == 0 ? String.valueOf((int)amount) : String.valueOf(amount);
            double euroAmount = convert2euro(amount);
            String euroStr = euroAmount % 1 == 0 ? String.format("%.0f", euroAmount) : df.format(euroAmount);
            System.out.println(bdAmount + "BD is equal to " + euroStr + " Euros");        }
    } while (amount != -99);
}

// This method is used to complete the currency conversion
public static double convert2euro(double bd) {
    return bd * 1.85;
}

Question 3

private static final int MIN_TEAM_SIZE = 2; //IDA
private static final int MAX_TEAM_SIZE = 5; //IDA
private static final int MIN_STUDENTS = 1; //IDA

public static int formGroups() { //IDA
    int totalStudents = 0; //IDA
    do{ //IDA
        System.out.println("How many students are in the group?"); //IDA
        if (input.hasNextInt()) { //IDA
            totalStudents = input.nextInt(); //IDA
            if (totalStudents < MIN_STUDENTS) { //IDA
                System.out.println("Error: total number of students must be positive"); //IDA
            }
        } else {
            input.next(); // IDA
            System.out.println("Error: total number of students must be positive"); //IDA
        } //IDA 
    } while (totalStudents < MIN_STUDENTS); //IDA
    return totalStudents; //IDA
} //IDA

public static int enterTeamSize() { //IDA
    int teamSize = 0; //IDA
    do { //IDA 
        System.out.println("How many students should be in each team?"); //IDA 
        if (input.hasNextInt()) { //IDA
            teamSize = input.nextInt(); //IDA
            if (teamSize < MIN_TEAM_SIZE || teamSize > MAX_TEAM_SIZE) { //IDA
                System.out.println("Error: team size must be between " + MIN_TEAM_SIZE + " and " + MAX_TEAM_SIZE); //IDA
            } //IDA
        } else { //IDA
            input.next(); //IDA 
            System.out.println("Error: team size must be between " + MIN_TEAM_SIZE + " and " + MAX_TEAM_SIZE); //IDA
        }
    } while (teamSize < MIN_TEAM_SIZE || teamSize > MAX_TEAM_SIZE); //IDA
    return teamSize; //IDA
}

public static void calculateNbTeams(int numberOfStudents, int teamSize) { //IDA
    int nbTeams = numberOfStudents / teamSize; //IDA
    int leftOut = numberOfStudents % teamSize; //IDA
    System.out.println("There will be " + nbTeams + " teams"); //IDA
    System.out.println("There will be " + leftOut + " students who have no team"); //IDA
}

Question 4

public static void menu() {
    // Constants
    final String CORRECT_PASSWORD = "pwd123";
    final int MIN_MENU_CHOICE = 1;
    final int MAX_MENU_CHOICE = 4;

    Scanner input = new Scanner(System.in);
    boolean authenticated = false;

    // Password verification loop using do-while
    do {
        System.out.println("Enter your password");
        String passwordAttempt = input.nextLine();

        if (passwordAttempt.equals(CORRECT_PASSWORD)) {
            authenticated = true;
        } else {
            System.out.println("Invalid password");
        }
    } while (!authenticated);

    // Display menu options
    System.out.println("1. Choice 1");
    System.out.println("2. Choice 2");
    System.out.println("3. Choice 3");
    System.out.println("4. Choice 4");

    // Get menu choice
    int choice = input.nextInt();

    // Validate and process choice
    if (choice >= MIN_MENU_CHOICE && choice <= MAX_MENU_CHOICE) {
        System.out.println("You have entered choice " + choice);
    } else {
        System.out.println("You have entered an invalid choice");
    }

    input.close();
}

Question 5



    public static void menu() {
        // Constants
        final String CORRECT_PASSWORD = "pwd123";
        final int MIN_MENU_CHOICE = 1;
        final int MAX_MENU_CHOICE = 4;

        Scanner input = new Scanner(System.in);
        boolean authenticated = false;
        boolean programRunning = true;

        // Password verification loop
        do {
            System.out.println("Enter your password");
            String passwordAttempt = input.nextLine();

            if (passwordAttempt.equals(CORRECT_PASSWORD)) {
                authenticated = true;
            } else {
                System.out.println("Invalid password");
            }
        } while (!authenticated);

        // Main program loop
        while (programRunning) {
            // Display menu options
            System.out.println("1. Choice 1");
            System.out.println("2. Choice 2");
            System.out.println("3. Choice 3");
            System.out.println("4. Exit");

            // Get menu choice
            int choice = input.nextInt();
            input.nextLine(); // Consume newline

            // Process choice
            if (choice >= MIN_MENU_CHOICE && choice <= MAX_MENU_CHOICE) {
                if (choice == 4) {
                    programRunning = false;
                } else {
                    System.out.println("You have entered choice " + choice);
                }
            } else {
                System.out.println("You have entered an invalid choice");
            }
        }

    }

Question 6

public static void products(int startValue, int stopValue) {
    // Initialize product to 1 (multiplicative identity)
    int product = 1;

    // Loop through each integer from startValue to stopValue
    for (int i = startValue; i <= stopValue; i++) {
        product *= i; // Multiply current value with running product
    }

    // Display the final product
    System.out.println(product);
}

Question 7

public static void sumOfValues(int startValue, int stopValue, int step) {
    // Initialize sum to 0 (additive identity)
    int total = 0;

    // Loop through every 'step' integer from startValue to stopValue
    for (int i = startValue; i <= stopValue; i += step) {
        total += i; // Add current value to running total
    }

    // Display the final total
    System.out.println(total);
}

Question 8

public static void printOddNumber(int startValue, int stopValue) {
    // Loop through numbers from startValue to stopValue (inclusive)
    for (int i = startValue; i <= stopValue; i++) {
        // Check if current number is odd (bitwise AND operation)
        if ((i & 1) == 1) {
            System.out.println(i); // Print odd number
        }
    }
}

Question 9

public static void drawStars(int n) {
    // Check for invalid input (negative numbers)
    if (n < 0) {
        System.out.println("Invalid input");
        return;
    }

    // Outer loop for each row
    for (int i = 1; i <= n; i++) {
        // Inner loop for stars in current row
        for (int j = 1; j <= i; j++) {
            System.out.print("*");
        }
        // Move to next line after each row
        System.out.println();
    }
}

Question 10

public static void drawStars(int n, boolean isUpSideDown) {
    // Constants for validation
    final int MIN_VALUE = 1;

    // Validate input - must be positive integer
    if (n < MIN_VALUE) {
        System.out.println("Invalid input");
        return;
    }

    /*
     * Determine printing direction:
     * - For ascending (isUpSideDown=false): print from 1 to n stars
     * - For descending (isUpSideDown=true): print from n to 1 stars
     */
    if (isUpSideDown) {
        // Descending pattern
        for (int row = n; row >= MIN_VALUE; row--) {
            printStarRow(row);
        }
    } else {
        // Ascending pattern
        for (int row = MIN_VALUE; row <= n; row++) {
            printStarRow(row);
        }
    }
}

// Helper method to print a single row of stars
private static void printStarRow(int starCount) {
    for (int star = 1; star <= starCount; star++) {
        System.out.print("*");
    }
    System.out.println(); // Move to next line after each row
}