Skip to the content.
Unit 8 Lesson 8.1 Lesson 8.2 ASCII image Homework

Unit 8 - Homework

By Torin

  • HW Hack for 8.2:
  • HW Hack for 8.1:

    You are given a function below, and your goal is to match the table to match the 2d array provided in the function.

    public class Main {
        public static void main(String[] args) {
            String[][] array = {{"My", "A"}, {"AP", "Class"}, {"CS", "Rocks!"}};
            
            for (int col = 0; col < array[0].length; col++) {
                for (int row = 0; row < array.length; row++) {
                    System.out.print(array[row][col] + " ");
                }
            }
        }
    }
    
    Main.main(null);
    

    Of the following, which is the correct table for the 2d array provided in the function?

    A)

      1 2 3
    1 My CS Class
    2 AP A Rocks!

    B)

      1 2 3
    1 My AP CS
    2 A Class Rocks!

    C)

      1 2 3
    1 My AP Class
    2 Rocks! CS A

    Answer: B

    HW Hack for 8.2:

    Write a program to search through a 2d array to find the grade for John. You will be given a list of students and their grades and you must find the grade of John. If a student is not in the list, then return “Student not found”.

    Use this program as a template:

    public class GradeSearch {
        public static String searchGrade(String[][] grades, String name) {
             
            // TODO: Implement the logic to find the grade of the student with the given name
            // Loop through each row in the grades array
            for (String[] student : grades) {
            // Check if the first element (name) matches the search name
                if (student[0].equals(name)) {
            // If the name matches, return the second element (grade)
                    return student[1];
                }
            }
            // If the student is not found, return "Student not found"
            return "Student not found";
        }
    
        public static void main(String[] args) {
            // Sample 2D array with names and grades
            String[][] grades = {
                {"John", "93"},
                {"Alice", "85"},
                {"Bob", "78"},
                {"Eve", "92"}
            };
    
            // Test the search function
            String nameToSearch = "John";
            String grade = searchGrade(grades, nameToSearch);
            System.out.println(nameToSearch + "'s grade: " + grade);
    
            nameToSearch = "Charlie";
            grade = searchGrade(grades, nameToSearch);
            System.out.println(nameToSearch + "'s grade: " + grade);
        }
    }
    
    // Execute the main method to see the output
    GradeSearch.main(null);
    
    John's grade: 93
    Charlie's grade: Student not found
    

    Heres a hint, try to use enhanced for loops to check each row for the name John. If you find John, then return the grade. If you don’t find John, then return “Student not found”.