7.2 Homework

Hard Hack: “Simple Inventory Manager”

Problem Statement:

You are building a basic inventory system using Java’s ArrayList to manage a list of items in a store. You will implement functions to add, update, delete, and view items in the inventory.

Starting Inventory:
The inventory already contains the following items:

  • "Laptop", "Mouse", "Keyboard"

Your task is to:

  1. Add items to the inventory.
  2. Update an item at a specific position in the inventory.
  3. Delete an item from the inventory.
  4. View all the items currently in the inventory.

Directions:

  1. Create an ArrayList called inventory that holds strings representing the items.
  2. Implement the following methods:
    • addItem(ArrayList<String> inventory, String item): Adds an item to the inventory.
    • updateItem(ArrayList<String> inventory, int index, String newItem): Updates the item at the specified index.
    • deleteItem(ArrayList<String> inventory, int index): Deletes the item at the specified index.
    • viewInventory(ArrayList<String> inventory): Displays all the items in the inventory.
  3. In your main() method:
    • Initialize the inventory with the starting items.
    • Add one new item to the inventory.
    • Update the second item.
    • Delete the third item.
    • Display the final inventory.

Example Workflow:

  1. Start with the inventory: ["Laptop", "Mouse", "Keyboard"].
  2. Add "Monitor".
  3. Update "Mouse" to "Gaming Mouse".
  4. Delete "Keyboard".
  5. Display the final inventory.

Expectations:

  • Ensure valid index when updating or deleting items (handle out-of-bounds indices).
  • Use the get(), set(), add(), and remove() methods to manage the ArrayList.
  • After all operations, print the final version of the inventory using viewInventory().

import java.util.ArrayList;

public class InventoryManager {

    public static void addItem(ArrayList<String> inventory, String item) {
        inventory.add(item);
    }
    public static void updateItem(ArrayList<String> inventory, int index, String newItem) {
        if (index >= 0 && index < inventory.size()) {
            inventory.set(index, newItem);
        } else {
            System.out.println("Invalid index. Cannot update.");
        }
    }
    public static void deleteItem(ArrayList<String> inventory, int index) {
        if (index >= 0 && index < inventory.size()) {
            inventory.remove(index);
        } else {
            System.out.println("Invalid index. Cannot delete.");
        }
    }
    public static void viewInventory(ArrayList<String> inventory) {
        System.out.println("Current Inventory: " + inventory);
    }

    public static void main(String[] args) {
        ArrayList<String> inventory = new ArrayList<>();
        inventory.add("Laptop");
        inventory.add("Mouse");
        inventory.add("Keyboard");
        addItem(inventory, "Monitor");
        updateItem(inventory, 1, "Gaming Mouse");
        deleteItem(inventory, 2);
        viewInventory(inventory);
    }
}
InventoryManager.main(null);
Current Inventory: [Laptop, Gaming Mouse, Monitor]

7.4 Homework:

(Paragraph Answer)

  1. What is the difference between the two examples above. Which one is better and why?

(Code Answer)

  1. Make your own algorithm using ArrayLists that finds the sum of the elements in the ArrayList

  2. I believe that using Arrays would be better since we technically have no need to really add elements to the array currently making it useless to use an Arraylist. Apart from this with my experience in competitive programming, Arrays are known to be much better to use when you can since they are faster.

// Problem 2
public Double findsum(ArrayList<Double>numbers){
    double sum = 0; for (Double i:numbers)sum += i;
    return sum;
}

ArrayList<Double>numbers=new ArrayList<>();
numbers.add(1.0);
numbers.add(2.0);
numbers.add(3.0);
System.out.println(findsum(numbers));
6.0

7.5 Homework

  • Imagine you’re an online E-store that sells video games. Use linear searching to help Aidan find if the game, Grand Theft Auto V, is offered in the E-store. If it is, tell him the price. If it isn’t, tell him where he can find it
import java.util.ArrayList;

public class searchString {
    public static void main(String[] args) {
        ArrayList<String> videoGames = new ArrayList<String>();
        videoGames.add("Roblox");
        videoGames.add("Fortnite");
        videoGames.add("Valorant");
        videoGames.add("Apex Legends");
        videoGames.add("GTA V");
        int index=0;
        for(String i:videoGames){
            if(i.equals("GTA V")){
                System.out.println("Found at index "+index);
            }
            index+=1;
        }
    }
}
searchString.main(null);
Found at index 4

7.6 Homework

  • You’re a teacher for a computer science class at Rancho Bernardo. You have a list of all the grades of the students in your class but its hard to see who has the highest and lowest grade. Use either insertion sort or selection sort to sort the ArrayList so the grades are easy to see.
import java.util.ArrayList;

public class SortTest
{
    public static void someSortingAlgorithm(ArrayList<Integer> elements) //insertion sort is so yummy
    {   
        int i = 1;
        while (i < elements.size()) {
            int current = elements.get(i);
            int j = i - 1; // starting from the last index before the element we are on
            while (j >= 0 && elements.get(j) > current) { // lets traverse till we reach the begining of the array and if the current index is less than the element keep moving it back to its goal position(yum emoji)
                elements.set(j + 1, elements.get(j));
                j--;
            }
            elements.set(j + 1,current);
            i++;
        }
        System.out.println(elements); // we print our beautiful array here
        
    }

    public static void main(String[] args) //why rbhs
    {
        ArrayList<Integer> arr1 = new ArrayList<>();
        arr1.add(85);
        arr1.add(92);
        arr1.add(76);
        arr1.add(88);
        arr1.add(67);
        arr1.add(94);
        arr1.add(73);
        arr1.add(89);
        arr1.add(91);
        arr1.add(82);
        arr1.add(78);
        arr1.add(88);
        arr1.add(95);
        arr1.add(60);
        arr1.add(84);
        arr1.add(77);
        arr1.add(91);
        arr1.add(68);
        arr1.add(97);
        arr1.add(83);
        someSortingAlgorithm(arr1);

        /* code */
    }
}
SortTest.main(null);
[60, 67, 68, 73, 76, 77, 78, 82, 83, 84, 85, 88, 88, 89, 91, 91, 92, 94, 95, 97]

7.7 Homework Problem: Exploring Hashing and Privacy Protection (Extra Credit)

Problem:

Write a Java program that simulates how hashing works in protecting passwords. You will implement the following tasks:

  1. Task 1: Basic Password Hashing
    • Write a program that accepts a user’s password input and generates a hash using the hashCode() method.
    • Display the original password and the hash to show how the same input always produces the same hash.
  2. Task 2: Salting the Password
    • Enhance the program by generating a random salt for the password. Append the salt to the password before hashing, and display both the salt and the hashed password.
    • Store the salt separately and demonstrate that the same password with a different salt produces a different hash.
  3. Task 3: Verifying the Password
    • Write a method that simulates logging in by taking a password and salt as input, hashing them again, and comparing the result to the previously stored hash.
    • If the hash matches, display “Login Successful”; otherwise, display “Login Failed.”

Extra Challenge (Optional):

  • Research and use the MessageDigest class in Java to implement password hashing with a more secure algorithm like SHA-256. Modify your program to use this instead of hashCode().
import java.security.*;
import java.util.*;
import java.nio.charset.StandardCharsets;

// Problem 1
public String hashcode(String password){
    return String.valueOf(password.hashCode());
}
System.out.println(hashcode("Thing"));
System.out.println(hashcode("Thing"));

// Problem 2(Lets add a bit of salt shall we)
public static String generateSalt() { 
    SecureRandom random = new SecureRandom();
    byte[] yummysalt = new byte[2];
    random.nextBytes(yummysalt);
    return Base64.getEncoder().encodeToString(yummysalt);
}
String password="Thing";
String passSalt1=hashcode(password+generateSalt());
String passSalt2=hashcode(password+generateSalt());
System.out.println(passSalt1==passSalt2);
System.out.println(passSalt1+" "+passSalt2);

// Problem 3

public class User {
    private String salt;
    private String hashedPassword;

    public User(String password) throws NoSuchAlgorithmException {
        this.salt = generateSalt();
        this.hashedPassword = hashPassword(password);
    }

    private static String generateSalt() { 
        SecureRandom random = new SecureRandom();
        byte[] yummysalt = new byte[16];
        random.nextBytes(yummysalt);
        return Base64.getEncoder().encodeToString(yummysalt);
    }

    private String hashPassword(String password) throws NoSuchAlgorithmException {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] hash = digest.digest(password.getBytes(StandardCharsets.UTF_8));
        StringBuilder hexString = new StringBuilder();
        for (byte b : hash) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }
        return hexString.toString(); // Return hashed password as hex string yum emoji
        // return String.valueOf((password + this.salt).hashCode());
    }

    public String verifyPassword(String password) throws NoSuchAlgorithmException {
        if (hashPassword(password).equals(this.hashedPassword)) {
            return "Login is successful";
        }
        return "Login failed";
    }
}

// Testing code
ArrayList<User> users = new ArrayList<>();

User user1 = new User("Secret");
User user2 = new User("Secret");

users.add(user1);
users.add(user2);

String entered = "Secret";
System.out.println(users.get(0).verifyPassword(entered));
System.out.println(users.get(1).verifyPassword(entered));

String badEntered = "peepeepoopoo";
System.out.println(users.get(0).verifyPassword(badEntered));
System.out.println(users.get(1).verifyPassword(badEntered));


80778446
80778446
false
1306877813 1306624233
Login is successful
Login is successful
Login failed
Login failed