Skip to the content.

Unit 4 Hacks

Fun While Loop Hack:

  • find and fix the missing increment in the while loop
int i = 0;
while (i < 5) {
    System.out.println(i);
    i++;  // Incrementing i to avoid an infinite loop
}
0
1
2
3
4

Fun For Loop Hack:

Create a program that iterates through a list of numbers (int_list = {0, 4, 51, 83, 92, 10, 123, 145}) using both a for loop and a for each loop, then split the numbers in the list into even/odd lists, and output them.

import java.util.ArrayList;

public class FunForLoopHack {
    public static void main(String[] args) {
        // Initial list of numbers
        int[] int_list = {0, 4, 51, 83, 92, 10, 123, 145};
        
        // Creating separate lists for even and odd numbers
        ArrayList<Integer> evenNumbers = new ArrayList<>();
        ArrayList<Integer> oddNumbers = new ArrayList<>();
        
        // Using a regular for loop to iterate and split numbers
        System.out.println("Using for loop:");
        for (int i = 0; i < int_list.length; i++) {
            int num = int_list[i];
            System.out.println(num);
            if (num % 2 == 0) {
                evenNumbers.add(num);
            } else {
                oddNumbers.add(num);
            }
        }
        
        // Clear the lists for the next approach (optional)
        evenNumbers.clear();
        oddNumbers.clear();
        
        // Using a for-each loop to iterate and split numbers
        System.out.println("\nUsing for-each loop:");
        for (int num : int_list) {
            System.out.println(num);
            if (num % 2 == 0) {
                evenNumbers.add(num);
            } else {
                oddNumbers.add(num);
            }
        }
        
        // Output the even and odd lists
        System.out.println("\nEven numbers: " + evenNumbers);
        System.out.println("Odd numbers: " + oddNumbers);
    }
}
FunForLoopHack.main(null);
Using for loop:
0
4
51
83
92
10
123
145

Using for-each loop:
0
4
51
83
92
10
123
145

Even numbers: [0, 4, 92, 10]
Odd numbers: [51, 83, 123, 145]

Popcorn Hack:

Iterate through the characters a string with a while loop

public class PopcornHack {
    public static void main(String[] args) {
        String text = "Popcorn Hack";
        int index = 0;
        
        // Using a while loop to iterate through the string
        while (index < text.length()) {
            // Print each character
            System.out.println(text.charAt(index));
            index++; // Move to the next character
        }
    }
}
PopcornHack.main(null);
P
o
p
c
o
r
n
 
H
a
c
k

Homework Hack!

code a caesar cipher that will encrypt any string with any key provided. your code should go into the encrypt() method, and should successfully pass the test cases provided as a bonus, try to use StringBuilder

public class CaesarCipher {
    private int key;
    private String phrase;

    public CaesarCipher(int key, String phrase) {
        this.key = key;
        this.phrase = phrase;
    }

    public String encrypt() {
        StringBuilder encrypted = new StringBuilder();
        for (int i = 0; i < phrase.length(); i++) {
            char currentChar = phrase.charAt(i);

            if (Character.isLetter(currentChar)) {
                char base = Character.isLowerCase(currentChar) ? 'a' : 'A';
                // Shift the character within the alphabet range
                char shiftedChar = (char) ((currentChar - base + key) % 26 + base);
                encrypted.append(shiftedChar);
            } else {
                // If it's not a letter, keep it as is
                encrypted.append(currentChar);
            }
        }
        return encrypted.toString();
    }

    public static void main(String[] args) {
        CaesarCipher test1 = new CaesarCipher(3, "hello world");
        CaesarCipher test2 = new CaesarCipher(10, "abcdefg");
        CaesarCipher test3 = new CaesarCipher(20, "i love csa");

        System.out.println("test 1: " + test1.encrypt()); // khoor zruog
        System.out.println("test 2: " + test2.encrypt()); // klmnopqrst
        System.out.println("test 3: " + test3.encrypt()); // c fihy wmu
    }
}
CaesarCipher.main(null);
test 1: khoor zruog
test 2: klmnopq
test 3: c fipy wmu

Fun Stubstring Hack:

Create a program that scrables any word that you put in, by reversing the first and last letters, then reversing the center letters. (example: sold becomes dlos, computer becomes retupmoc)

import java.util.Scanner;

public class FunStubstringHack {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Prompt user for input
        System.out.println("Enter a word to scramble: ");
        String word = scanner.nextLine();

        // Scramble the word
        String scrambledWord = scrambleWord(word);

        // Output the result
        System.out.println("Scrambled word: " + scrambledWord);
    }

    public static String scrambleWord(String word) {
        // Handle words with less than 2 characters
        if (word.length() < 2) {
            return word; // No scrambling needed
        }

        // Get the first and last letters
        char firstLetter = word.charAt(0);
        char lastLetter = word.charAt(word.length() - 1);

        // Get the center letters
        String centerLetters = word.substring(1, word.length() - 1);

        // Reverse the center letters
        String reversedCenter = new StringBuilder(centerLetters).reverse().toString();

        // Construct the scrambled word
        return lastLetter + reversedCenter + firstLetter;
    }
}
FunStubstringHack.main(null);
Enter a word to scramble: 
Scrambled word: rebotco

What is wrong with this code cell(Hack)

import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int rows = scanner.nextInt();
for (int i = rows; i>1; i-) {
    // Print numbers from 1 to i
    for (int j = 1; j <= i; j++) {
        System.out.print(j + " ");
    }
    // Move to next line after each row
    System.out.println();
    }
        
scanner.close();

Answer: In the loop for (int i = rows; i > 1; i-), the decrement operator is incorrectly written as i-. It should be i-- to properly decrement the value of i in each iteration. This causes the loop not to execute as expected.

Screenshot 2024-09-19 at 20 45 04

Answer: B. 20

Explanation: The loop will run 5 times because 8-3 is 5. Then in each loop, there are more loops, each time 4 loops because 5-1 is 4. If i do 5 times 4, I get 20, which is the answer.

question

This will print * 24 times in a new line because the outer loop runs 6 times and the inner loop runs 4 times, so the code will be run 24 times, giving us * 24 times.

Question 1:

What does the following code print?

A. 5 6 7 8 9

B. 4 5 6 7 8 9 10 11 12

C. 3 5 7 9 11

D. 3 4 5 6 7 8 9 10 11 12

for (int i = 3; i <= 12; i++)
{
   System.out.print(i + " ");
}

Answer: D

Question 2:

How many times does the following method print a *?

A. 9

B. 7

C. 6

D. 10

for (int i = 3; i < 9; i++)
{
   System.out.print("*");
}

Answer: C

Question 3:

What does the following code print?

A. 5 4 3 2 1

B. -5 -4 -3 -2 -1

C. -4 -3 -2 -1 0

int x = -5;
while (x < 0)
{
   x++;
   System.out.print(x + " ");
}

Answer: C

Loops homework hack

Easy Hack

  • use a while loop to find the numbers from 1-50 that are divisible by 3 or 5, then store them into a list (make sure to print it out at the end)
  • use a for loop to do the same thing detailed above
import java.util.ArrayList;

public class DivisibleByThreeOrFiveWhile {
    public static void main(String[] args) {
        ArrayList<Integer> divisibleNumbers = new ArrayList<>();
        int i = 1; // Start from 1

        // Use a while loop to find numbers from 1 to 50
        while (i <= 50) {
            if (i % 3 == 0 || i % 5 == 0) {
                divisibleNumbers.add(i);
            }
            i++; // Increment i
        }

        // Print the result
        System.out.println("Numbers from 1 to 50 that are divisible by 3 or 5 (using while loop): " + divisibleNumbers);
    }
}
DivisibleByThreeOrFiveWhile.main(null);
Numbers from 1 to 50 that are divisible by 3 or 5 (using while loop): [3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50]
import java.util.ArrayList;

public class DivisibleByThreeOrFiveFor {
    public static void main(String[] args) {
        ArrayList<Integer> divisibleNumbers = new ArrayList<>();

        // Use a for loop to find numbers from 1 to 50
        for (int i = 1; i <= 50; i++) {
            if (i % 3 == 0 || i % 5 == 0) {
                divisibleNumbers.add(i);
            }
        }

        // Print the result
        System.out.println("Numbers from 1 to 50 that are divisible by 3 or 5 (using for loop): " + divisibleNumbers);
    }
}
DivisibleByThreeOrFiveFor.main(null);
Numbers from 1 to 50 that are divisible by 3 or 5 (using for loop): [3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50]

Harder Hack

Palindromes are numbers that have the same value when reversed (ex: “123321” or “323”). Create a program that uses a while loop that outputs all palindromes in any given list.

Sample Input: test_list = [5672, 235, 5537, 6032, 317, 8460, 1672, 8104, 7770, 4442, 913, 2508, 1116, 9969, 9091, 522, 8756, 9527, 7968, 1520, 4444, 515, 2882, 6556, 595]

Sample Output: 4444, 515, 2882, 6556, 595

import java.util.ArrayList;

public class PalindromeFinder {
    public static void main(String[] args) {
        // Sample input list
        int[] testList = {5672, 235, 5537, 6032, 317, 8460, 1672, 8104, 7770, 
                          4442, 913, 2508, 1116, 9969, 9091, 522, 8756, 
                          9527, 7968, 1520, 4444, 515, 2882, 6556, 595};

        ArrayList<Integer> palindromes = new ArrayList<>();
        int index = 0;

        // Use a while loop to iterate through the testList
        while (index < testList.length) {
            if (isPalindrome(testList[index])) {
                palindromes.add(testList[index]);
            }
            index++; // Increment index
        }

        // Print the result
        System.out.println("Palindromes in the list: " + palindromes);
    }

    // Method to check if a number is a palindrome
    public static boolean isPalindrome(int number) {
        String strNumber = Integer.toString(number); // Convert number to string
        int left = 0;
        int right = strNumber.length() - 1;

        // Check if the string is a palindrome
        while (left < right) {
            if (strNumber.charAt(left) != strNumber.charAt(right)) {
                return false; // Not a palindrome
            }
            left++;
            right--;
        }
        return true; // It's a palindrome
    }
}
PalindromeFinder.main(null);
Palindromes in the list: [4444, 515, 2882, 6556, 595]

Coding Hack(For above 0.9):

Use a for loop to output a spiral matrix with size n

For example:

Sample Input: 3

Output: [[1, 2, 3], [8, 9, 4], [7, 6, 5]]

import java.util.Arrays;

public class SpiralMatrix {
    public static void main(String[] args) {
        int n = 3; // Sample input size
        int[][] matrix = new int[n][n]; // Create a 2D array for the spiral matrix

        int top = 0, bottom = n - 1; // Initialize top and bottom boundaries
        int left = 0, right = n - 1; // Initialize left and right boundaries
        int num = 1; // Start filling the matrix from 1

        // Fill the matrix in a spiral order
        for (int i = 0; i < n * n; i++) {
            if (top <= bottom) {
                for (int j = left; j <= right; j++) {
                    matrix[top][j] = num++;
                }
                top++; // Move the top boundary down
            }

            if (left <= right) {
                for (int j = top; j <= bottom; j++) {
                    matrix[j][right] = num++;
                }
                right--; // Move the right boundary left
            }

            if (top <= bottom) {
                for (int j = right; j >= left; j--) {
                    matrix[bottom][j] = num++;
                }
                bottom--; // Move the bottom boundary up
            }

            if (left <= right) {
                for (int j = bottom; j >= top; j--) {
                    matrix[j][left] = num++;
                }
                left++; // Move the left boundary right
            }
        }

        // Print the spiral matrix
        System.out.println("Spiral Matrix of size " + n + ":");
        for (int[] row : matrix) {
            System.out.println(Arrays.toString(row));
        }
    }
}
SpiralMatrix.main(null);
Spiral Matrix of size 3:
[1, 2, 3]
[8, 9, 4]
[7, 6, 5]