Week 16

Source Code

import java.util.*;

public class Week16 {
    public static void main(String[] args) {
        String myName = ""; // add your name
        System.out.println("Week 16" + " - " + myName);

        // Menu
        System.out.println("Menu");
        System.out.println("E1 - Example 1");
        System.out.println("Q  - Quit");

        // setup Scanner
        Scanner in = new Scanner(System.in);
        System.out.print("Choice: ");
        String choice = in.nextLine();

        // switch choices
        switch (choice) {
            case "E1":
                System.out.println("Example 1");
                example1();
                break;
            case "E2":
                System.out.println("Example 2");
                example2();
                break;
            case "E3":
                System.out.println("Example 3");
                example3();
                break;
            case "E4":
                System.out.println("Example 4");
                example4();
                break;
            case "E5":
                System.out.println("Example 5");
                example5();
                break;
            case "Q":
                System.out.println("Quitting..!");
                break;
        }
    }

    // example1 method
    public static void example1() {
        // create an array of friends
        

        // for loop
        

        // enhanced for loop
        

    }

    // example2 method
    public static void example2() {
        // create an array of horses
        

        // enhanced for loop
        

    }

    // example3 method
    public static void example3() {
        // create array
        int[] values = { 6, 2, 1, 7, 12, 5 };

        // assign first value
        int first = values[0];

        // loop
        
            // if it's not the last element, copy the next one over
            
                // last element gets first
               
            
        
        // print
       

    }

    // example4 method
    public static void example4() {
        Scanner in = new Scanner(System.in);

        System.out.print("Enter the number of elements: ");
        int n = in.nextInt();
        int[] values = new int[n];

        System.out.print("Enter the elements:");
        for (int i = 0; i < n; i++) {
            values[i] = in.nextInt();
        }

        // Checking for adjacent duplicates
        
        
    }

    // example5 method
    public static void example5() {
        Scanner in = new Scanner(System.in);

        System.out.print("Enter the number of elements: ");
        int n = in.nextInt();
        int[] values = new int[n];

        System.out.print("Enter the elements:");
        for (int i = 0; i < n; i++) {
            values[i] = in.nextInt();
        }

        // Checking for any duplicates in the array
        
    }

    // Method to check for adjacent duplicates
    public static boolean hasAdjacentDuplicates(int[] values) {
        for (int i = 0; i < values.length - 1; i++) {
            if (values[i] == values[i + 1]) {
                return true;
            }
        }
        return false;
    }

    // Method to check for duplicates anywhere in the array
    public static boolean hasAnyDuplicates(int[] values) {
        for (int i = 0; i < values.length; i++) {
            for (int j = i + 1; j < values.length; j++) {
                if (values[i] == values[j]) {
                    return true;
                }
            }
        }
        return false;
    }

    // printArray method
    public static void printArray(int[] arr) {
        System.out.println("Print Array");
        System.out.println("Index\tValue");
        for (int i = 0; i < arr.length; i++) {
            System.out.println(i + "\t" + arr[i]);
        }
    }
}

CommandLineArgs.java

public class CommandLineArgs {
    public static void main(String[] args) {
        System.out.println("Number of arguments: " + args.length);
        for (int i = 0; i < args.length; i++) {
            System.out.println("Argument " + i + ": " + args[i]);
        }
    }
}

CommandLineSum.java

public class CommandLineSum {
    public static void main(String[] args) {
        if (args.length < 2) {
            System.out.println("Please provide two numbers.");
            return;
        }

        int num1 = Integer.parseInt(args[0]);
        int num2 = Integer.parseInt(args[1]);
        int sum = num1 + num2;

        System.out.println("Sum: " + sum);
    }
}

W16Problem1.java

import java.util.*;

public class W16Problem1
{
    public static void main(String[] args)
    {
        System.out.println("Problem 1");
        // Array to store 1000 random numbers

                
        // Array to track occurrences of numbers 1-100       

                
        // Fill the first array with random numbers from 1 to 10
        
        
        // Count the occurrences using an enhanced for loop
        // Adjust index since 1 should go to index 0


        // Print frequency of each number
        
        
    }
}

W16Problem2.java

import java.util.*;

public class W16Problem2
{
    public static void main(String[] args)
    {
        System.out.println("Problem 2");
        // Array to hold 10000 random numbers

                
        // Array to store frequency counts (index 0 for 0, index 99 for 99)   

                
        // Fill the first array with random numbers from 0 to 99
        
        
        // Sort the array in ascending order
        
        
        // Count occurrences of each number using an enhanced for loop
        // by incrementing the corresponding index in frequency array


        // Find most and least frequent numbers
        // Create variables to track the most and least frequent numbers
        
        
        // Print the frequency of each number in the range 0-99
        
        
        // Print the most and least frequent numbers
        
        
    }
}

W16Problem3.java

public class W16Problem3 {
    public static boolean hasConsecutiveIncreasing(int[] values) {
        // TODO: Implement logic to check for consecutive increasing numbers
        
        return false;
    }

    public static void main(String[] args) {
        // Test 1
        int[] values1 = {1, 2, 3, 5, 7}; 
        // Expected output: true
        System.out.println(hasConsecutiveIncreasing(values1)); 
        
        // Test 2
        int[] values2 = {1, 1, 1, 1, 1}; 
        // Expected output: false
        System.out.println(hasConsecutiveIncreasing(values2)); 
                
    }
}

W16Problem4.java

public class W16Problem4 {
    public static boolean hasPairWithSum(int[] values, int targetSum) {
        // TODO: Implement logic to check if any two elements sum to targetSum
        
        return false;
    }

    public static void main(String[] args) {
        // Test 1
        int[] values1 = {4, 7, 1, 2, 8};
        int targetSum1 = 9;
        // Expected output: true
        System.out.println(hasPairWithSum(values1, targetSum1));

        // Test 2
        int[] values2 = {1, 7, 1, 3, 10};
        int targetSum2 = 9;
        // Expected output: false
        System.out.println(hasPairWithSum(values2, targetSum2));
    
    }
}

W16Problem5.java

public class W16Problem5 {
    public static int countUniqueElements(int[] values) {
        // TODO: Implement logic to count unique elements
        
        return 0;
    }

    public static void main(String[] args) {
        // Test 1
        int[] values1 = {1, 2, 3, 2, 4, 1, 5}; 
        // Expected output: 5
        System.out.println(countUniqueElements(values1)); 
        
        // Test 2
        int[] values2 = {1, 2, 1, 2, 1, 2, 1}; 
        // Expected output: 2
        System.out.println(countUniqueElements(values2));    
                   
    }
}

W16Problem6.java

public class W16Problem6 {
    public static void main(String[] args) {
        // Create an array of size 10000


        // Fill array with random numbers from 0 to 99
        

        // Sort the array to group identical numbers together
        

        // Variables to track current count and mode
        
        
        // Variables to track minimum frequency
        

        // Count consecutive occurrences
        
        
                // Same number continues


                // Check if previous run is the mode

                
                // Check if previous run is the minimum (excluding the current run)


                // Reset count for new number





        // Print results



    }
}

Horse.java

public class Horse {
    private String name;
    private int weight;

    public Horse(String name, int weight) {
        this.name = name;
        this.weight = weight;
    }

    public String getName() {
        return name;
    }

    public int getWeight() {
        return weight;
    }
}

HorseBarn.java

/**
 * HorseBarn - A class to manage horses in a barn with numbered spaces.
 * Each space can hold at most one horse, and each horse has a unique name.
 */
public class HorseBarn {
    // Instance Variables
    private Horse[] spaces; // Array to store horses, null represents empty space

    /**
     * Constructor for HorseBarn
     *
     * @param numberOfSpaces the number of spaces in the barn
     */
    public HorseBarn(int numberOfSpaces) {
        spaces = new Horse[numberOfSpaces];
    }

    /**
     * Returns the index of the space that contains the horse with the specified
     * name.
     *
     * @param name the name of the horse to find
     * @return the index of the space containing the horse with the specified name;
     *         -1 if no horse with the specified name is in the barn.
     */
    public int findHorseSpace(String name) {
        // Input validation
        if (name == null) {
            return -1;
        }

        // Search through all spaces
        for (int i = 0; i < spaces.length; i++) {
            // Check if space has a horse and if the names match
            if (spaces[i] != null && spaces[i].getName().equals(name)) {
                return i;
            }
        }

        // Horse not found
        return -1;
    }

    /**
     * Consolidates the barn by moving horses so that the horses are in adjacent
     * spaces,
     * starting at index 0, with no empty space between any two horses.
     * The order of the horses remains the same as before the consolidation.
     */
    public void consolidate() {
        // Create temporary array
        Horse[] temp = new Horse[spaces.length];
        int nextPosition = 0;

        // Copy non-null horses in order
        for (int i = 0; i < spaces.length; i++) {
            if (spaces[i] != null) {
                temp[nextPosition] = spaces[i];
                nextPosition++;
            }
        }

        // Replace original array with consolidated version
        spaces = temp;
    }

    /**
     * Adds a horse to the first available (empty) space in the barn.
     *
     * @param horse the horse to add
     * @return true if the horse was added successfully, false if the barn is full
     *         or if a horse with the same name already exists
     */
    public boolean addHorse(Horse horse) {
        // Input validation
        if (horse == null) {
            return false;
        }

        // Check if horse with same name already exists
        if (findHorseSpace(horse.getName()) != -1) {
            return false;
        }

        // Find first empty space
        for (int i = 0; i < spaces.length; i++) {
            if (spaces[i] == null) {
                spaces[i] = horse;
                return true;
            }
        }

        // No empty space found
        return false;
    }

    /**
     * Removes a horse from the barn by name.
     *
     * @param name the name of the horse to remove
     * @return true if the horse was removed successfully, false if the horse wasn't
     *         found
     */
    public boolean removeHorse(String name) {
        int index = findHorseSpace(name);
        if (index != -1) {
            spaces[index] = null;
            return true;
        }
        return false;
    }

    /**
     * Returns the horse at the specified index.
     *
     * @param index the index of the space to check
     * @return the horse at the specified space, or null if the space is empty
     *         or the index is invalid
     */
    public Horse getHorse(int index) {
        if (index >= 0 && index < spaces.length) {
            return spaces[index];
        }
        return null;
    }

    /**
     * Returns the number of spaces in the barn.
     *
     * @return the total number of spaces
     */
    public int getSpaces() {
        return spaces.length;
    }

    /**
     * Returns the number of horses currently in the barn.
     *
     * @return the number of occupied spaces
     */
    public int getNumberOfHorses() {
        int count = 0;
        for (Horse horse : spaces) {
            if (horse != null) {
                count++;
            }
        }
        return count;
    }

    /**
     * Returns true if the barn is empty (contains no horses).
     *
     * @return true if the barn is empty, false otherwise
     */
    public boolean isEmpty() {
        return getNumberOfHorses() == 0;
    }

    /**
     * Returns true if the barn is full (all spaces occupied).
     *
     * @return true if the barn is full, false otherwise
     */
    public boolean isFull() {
        return getNumberOfHorses() == spaces.length;
    }

    /**
     * Returns a string representation of the barn.
     *
     * @return a string showing the contents of each space in the barn
     */
    @Override
    public String toString() {
        StringBuilder result = new StringBuilder();
        result.append("HorseBarn with ").append(spaces.length).append(" spaces:\n");
        for (int i = 0; i < spaces.length; i++) {
            result.append("Space ").append(i).append(": ");
            if (spaces[i] == null) {
                result.append("empty");
            } else {
                result.append(spaces[i].getName()).append(" (").append(spaces[i].getWeight()).append(" lbs)");
            }
            result.append("\n");
        }
        return result.toString();
    }

    public static void main(String[] args) {
        // Create test barn
        

        // Test 1: Empty barn
        

        // Add horses
        

        // print the barn layout
        

        // Test 2: Find existing horses
        

        // Test 3: Find non-existent horse
        

        // Test 4: Consolidate
        
        
    }
}

Vehicle.java

public class Vehicle {
    private String licensePlate;
    private String make;
    private String model;
    
    public Vehicle(String licensePlate, String make, String model) {
        this.licensePlate = licensePlate;
        this.make = make;
        this.model = model;
    }
    
    public String getLicensePlate() { return licensePlate; }
    public String getMake() { return make; }
    public String getModel() { return model; }
    
    @Override
    public String toString() {
        return make + " " + model + " (" + licensePlate + ")";
    }
}

ParkingGarage.java

public class ParkingGarage {
    private Vehicle[] spots;
    private static final double HOURLY_RATE = 5.00;  // $5 per hour
    
    public ParkingGarage(int numSpots) {
        spots = new Vehicle[numSpots];
    }
    
    /**
     * Parks a vehicle in the first available appropriate spot
     * @param vehicle the vehicle to park
     * @return the spot number if successful, -1 if no spots available
     */
    public int parkVehicle(Vehicle vehicle) {
        // TODO: Implement this method
        
        return -1;
    }
    
    /**
     * Removes a vehicle from the garage and calculates parking fee
     * @param licensePlate the license plate of the vehicle to remove
     * @return the parking fee in dollars, -1 if vehicle not found
     */
    public double removeVehicle(String licensePlate) {
        // TODO: Implement this method
        
        return -1.0;
    }
    
    /**
     * Finds a vehicle by license plate
     * @param licensePlate the license plate to search for
     * @return the spot number if found, -1 if not found
     */
    public int findVehicle(String licensePlate) {
        // TODO: Implement this method
        
        return -1;
    }

    /**
     * Returns a formatted string representing the parking garage layout.
     * Shows which spots are occupied and by which vehicle.
     * 
     * @return A string representation of the parking garage.
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("Parking Garage Status:\n");
        for (int i = 0; i < spots.length; i++) {
            sb.append("Spot ").append(i).append(": ");
            if (spots[i] != null) {
                sb.append(spots[i]); // Calls Vehicle's toString()
            } else {
                sb.append("Empty");
            }
            sb.append("\n");
        }
        return sb.toString();
    }

    /**
     * The main method for testing the Parking Garage Management System.
     */
    public static void main(String[] args) {
        System.out.println("Welcome to the Parking Garage!");
        // Create a parking garage with 10 spots
        

        // Create some vehicles
        Vehicle car1 = new Vehicle("ABC123", "Dodge", "Charger");
        Vehicle car2 = new Vehicle("XYZ789", "Honda", "Civic");
        Vehicle car3 = new Vehicle("LMN456", "Ford", "Escape");
        Vehicle car4 = new Vehicle("NULL", "Toyota", "Corolla");
        Vehicle car5 = new Vehicle("VROOM", "Dodge", "Challenger");

        // Park vehicles


        // Find vehicle (ask the user for a Vehicle to find)
        

        // Remove a vehicle and calculate fee


    }
}

Last updated

Was this helpful?