Here is the list of the unit 2 hacks.
Note: This is due Monday! Write your hacks in a Jupyter Notebook and then DM them to us over slack by Monday Morning at 8:00 AM. For full credit, all criteria in the hacks must be completed and show some originality.
Hack 1:
Create a void method that takes an integer input and adds it to an ArrayList. Then, add a non-void method that is able to call a certain index from the ArrayList.
public class SimpleArrayListExample {
private static ArrayList<Integer> integerList = new ArrayList<>();
public static void addToArrayList(int number) {
integerList.add(number);
}
public static int getFromArrayList(int index) {
return integerList.get(index);
}
public static void main(String[] args) {
integerList.add(1);
integerList.add(2);
integerList.add(3);
integerList.add(4);
integerList.add(5);
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number to add to the ArrayList: ");
int userInput = scanner.nextInt();
addToArrayList(userInput);
System.out.print("Enter the index you want to access (0-" + (integerList.size() - 1) + "): ");
int indexToAccess = scanner.nextInt();
if (indexToAccess >= 0 && indexToAccess < integerList.size()) {
int valueAtIndex = getFromArrayList(indexToAccess);
System.out.println("Value at index " + indexToAccess + ": " + valueAtIndex);
} else {
System.out.println("Invalid index.");
}
}
}
SimpleArrayListExample.main(null);
// User adds a number to an existing ArrayList and then selects an index from ArrayList to print.
// Potential Improvements:
// Input Validation: Add checks to ensure that the user input is a valid integer.
// Error Handling: Consider adding try-catch blocks to handle potential exceptions (e.g., if the user inputs a non-integer).
// Modularization: Depending on the complexity of the application, consider breaking down the code into smaller, more modular functions.
// User Feedback: Provide more informative messages for the user, especially in case of errors.
// Exception Handling: Handle possible exceptions that may occur when working with user input, such as InputMismatchException.
Enter a number to add to the ArrayList: Enter the index you want to access (0-5): Value at index 2: 3
Hack 2:
Create a simple guessing game with random numbers in math, except the random number is taken to a random exponent (also includes roots), and the person has to find out what the root and exponent is (with hints!). Use at least one static and one non-static method in your class.
public class MathGuessingGame {
private static Random random = new Random();
private static double generateRandomNumber() {
return random.nextInt(5) + 1;
}
private static int generateRandomExponent() {
return random.nextInt(4) + 2;
}
public static void main(String[] args) {
double base = generateRandomNumber();
int exponent = generateRandomExponent();
double result = Math.pow(base, exponent);
System.out.println("I have taken a random number to a random exponent.");
System.out.println("Can you guess the base and the exponent?");
Scanner scanner = new Scanner(System.in);
int guessBase;
int guessExponent;
do {
System.out.print("Guess the base: \n");
guessBase = scanner.nextInt();
System.out.print("Guess the exponent: \n");
guessExponent = scanner.nextInt();
if (guessBase == base && guessExponent == exponent) {
System.out.println("Congratulations! You guessed it!");
} else {
if (guessBase > base) {
System.out.println("Hint: Base is too high. \n");
} else {
System.out.println("Hint: Base is too low. \n");
}
if (guessExponent > exponent) {
System.out.println("Hint: Exponent is too high. \n");
} else {
System.out.println("Hint: Exponent is too low. \n");
}
}
} while (guessBase != base || guessExponent != exponent);
scanner.close();
}
}
MathGuessingGame.main(null);
// Generates a random base and exponent, calculates the result, and asks the user for their guesses.
// If the guesses are correct, a congratulatory message is displayed. Otherwise, hints are given to help the user refine their guesses.
// Possible improvements:
// Add input validation to handle non-integer inputs or out-of-range guesses.
// Implement a limit on the number of guesses allowed to prevent an infinite loop.
// Add a scoring system or timer to make the game more competitive.
// Provide more detailed feedback, such as how close the guesses are to the actual values.
// Implement a user-friendly interface for better user experience.
// Consider adding a difficulty level or option for the user to choose the range of numbers.
// Handle potential exceptions (e.g., if the user enters a non-integer value).
// Add comments to explain the purpose of each method for better code readability and maintainability.
// I thought about using doubles instead of integers but I knew this would make the game impossible to play
// I could improve this code by including error handling (not allowing non-numeric characters) displaying what your previous guess was so you don't guess it again, and I could also add a scoring system which tracks the number of guesses
I have taken a random number to a random exponent.
Can you guess the base and the exponent?
Guess the base:
Guess the exponent:
Hint: Base is too low.
Hint: Exponent is too low.
Guess the base:
Guess the exponent:
Hint: Base is too low.
Hint: Exponent is too low.
Guess the base:
Guess the exponent:
Hint: Base is too low.
Hint: Exponent is too low.
Guess the base:
Guess the exponent:
Congratulations! You guessed it!
Hack 3:
Create a class of your choosing that has multiple parameters of different types (int, boolean, String, double) and put 5 data values in that list. Show that you can access the information by giving some samples.
public class MyClass {
private int intValue;
private boolean boolValue;
private String stringValue;
private double doubleValue;
public MyClass(int intValue, boolean boolValue, String stringValue, double doubleValue) {
this.intValue = intValue;
this.boolValue = boolValue;
this.stringValue = stringValue;
this.doubleValue = doubleValue;
}
public int getIntValue() {
return intValue;
}
public boolean getBoolValue() {
return boolValue;
}
public String getStringValue() {
return stringValue;
}
public double getDoubleValue() {
return doubleValue;
}
public static void main(String[] args) {
MyClass obj1 = new MyClass(10, true, "Hello", 3.14);
MyClass obj2 = new MyClass(20, false, "World", 2.71);
MyClass obj3 = new MyClass(30, true, "Soham", 1.618);
MyClass obj4 = new MyClass(40, false, "Was", 0.577);
MyClass obj5 = new MyClass(50, true, "Here", 2.718);
System.out.println("Object 1:");
System.out.println("Int Value: " + obj1.getIntValue());
System.out.println("\n");
System.out.println("Object 2:");
System.out.println("Boolean Value: " + obj2.getBoolValue());
System.out.println("\n");
System.out.println("Object 3:");
System.out.println("String Value: " + obj3.getStringValue());
System.out.println("\n");
System.out.println("Object 4:");
System.out.println("Double Value: " + obj4.getDoubleValue());
System.out.println("\n");
System.out.println("Object 5:");
System.out.println("Int Value: " + obj5.getIntValue());
System.out.println("Boolean Value: " + obj5.getBoolValue());
System.out.println("String Value: " + obj5.getStringValue());
System.out.println("Double Value: " + obj5.getDoubleValue());
}
}
MyClass.main(null);
// Create five objects of MyClass and access their information using the getter methods.
// Potential improvements:
// Encapsulation: Consider adding setter methods if you want to allow external code to modify the values of the fields after the object is created.
// Error handling: Add appropriate error handling mechanisms, such as input validation or exception handling, especially when dealing with user input or external data.
// Modularity: Depending on the context, it might be beneficial to organize the code into multiple classes to improve code readability and maintainability.
// Testing: Consider writing unit tests to ensure the correctness of the MyClass class and its methods.
// Documentation: Add comments to the code to explain complex logic or any non-trivial behavior
// Naming Conventions: Ensure that class names, field names, and method names follow appropriate naming conventions to make the code more readable and understandable.
Object 1:
Int Value: 10
Object 2:
Boolean Value: false
Object 3:
String Value: Soham
Object 4:
Double Value: 0.577
Object 5:
Int Value: 50
Boolean Value: true
String Value: Here
Double Value: 2.718
Hack 4:
Using your preliminary knowledge of loops, use a for loop to iterate through a personโs first and last name, separated by a space, and create methods to call a personโs first name and a personโs last name by iterating through the string.
public class NameIterator {
private String fullName;
public NameIterator(String fullName) {
this.fullName = fullName;
}
public String getFirstName() {
int spaceIndex = fullName.indexOf(" ");
return fullName.substring(0, spaceIndex);
}
public String getLastName() {
int spaceIndex = fullName.indexOf(" ");
return fullName.substring(spaceIndex + 1, fullName.lastIndexOf(" "));
}
public String getEmojis() {
return fullName.substring(fullName.lastIndexOf(" ") + 1);
}
public static void main(String[] args) {
NameIterator nameIterator = new NameIterator("John Mortensen ๐๐๐๐");
System.out.println("First Name: " + nameIterator.getFirstName());
System.out.println("Last Name: " + nameIterator.getLastName());
System.out.println("Emojis: " + nameIterator.getEmojis());
}
}
NameIterator.main(null);
// Defines a PersonName class with methods to extract the first and last names from a full name string. It uses a for loop to iterate through the characters, identifying the space that separates the two names, and returns them accordingly.
// Possible improvements:
// Error handling: The code assumes that the input will always contain a space between the first and last names. Error handling could be added to handle cases where the input format is different.
// Input validation: Additional validation can be added to ensure that the input is not null or empty.
// Case handling: The code does not handle cases where the first and last names have leading/trailing spaces or where the names are in mixed case. These aspects could be considered for improvement.
First Name: John
Last Name: Mortensen
Emojis: ๐๐๐๐