Mr.Mou @ ShiShi AP Center

AP CSA



Array Algorithms with Different Loop Versions

1. Determine the Minimum or Maximum Value in an Array

Find Maximum Value

import java.util.Arrays;

public class ArrayAlgorithms {
    public static void main(String[] args) {
        int[] numbers = {3, 5, 1, 7, 9};

        // Using for loop
        int max = numbers[0];
        for (int i = 1; i < numbers.length; i++) {
            if (numbers[i] > max) {
                max = numbers[i];
            }
        }
        System.out.println("Max value (for loop): " + max);

        // Using enhanced for loop
        max = numbers[0];
        for (int num : numbers) {
            if (num > max) {
                max = num;
            }
        }
        System.out.println("Max value (enhanced for loop): " + max);
    }
}
  

2. Compute a Sum or Average of Array Elements

Compute Sum

public class ArraySum {
    public static void main(String[] args) {
        int[] numbers = {3, 5, 1, 7, 9};

        // Using for loop
        int sum = 0;
        for (int i = 0; i < numbers.length; i++) {
            sum += numbers[i];
        }
        System.out.println("Sum (for loop): " + sum);

        // Using enhanced for loop
        sum = 0;
        for (int num : numbers) {
            sum += num;
        }
        System.out.println("Sum (enhanced for loop): " + sum);
    }
}
  

Compute Average

public class ArrayAverage {
    public static void main(String[] args) {
        int[] numbers = {3, 5, 1, 7, 9};
        int sum = 0;
        
        // Using for loop to compute sum
        for (int i = 0; i < numbers.length; i++) {
            sum += numbers[i];
        }
        System.out.println("Sum (for loop): " + sum);

        // Compute average
        double average = (double) sum / numbers.length;
        System.out.println("Average: " + average);
    }
}
  

3. Search for a Particular Element in the Array

Search for the Number 7

public class ArraySearch {
    public static void main(String[] args) {
        int[] numbers = {3, 5, 1, 7, 9};
        int target = 7;
        boolean found = false;

        // Using for loop
        for (int i = 0; i < numbers.length; i++) {
            if (numbers[i] == target) {
                found = true;
                break;
            }
        }
        System.out.println("Found (for loop): " + found);

        // Using enhanced for loop
        found = false;
        for (int num : numbers) {
            if (num == target) {
                found = true;
                break;
            }
        }
        System.out.println("Found (enhanced for loop): " + found);
    }
}
  

4. Determine if At Least One Element Has a Particular Property

Check if at Least One Element is Even

public class ArrayProperty {
    public static void main(String[] args) {
        int[] numbers = {3, 5, 1, 7, 9};
        boolean hasEven = false;

        // Using for loop
        for (int i = 0; i < numbers.length; i++) {
            if (numbers[i] % 2 == 0) {
                hasEven = true;
                break;
            }
        }
        System.out.println("Has even (for loop): " + hasEven);

        // Using enhanced for loop
        hasEven = false;
        for (int num : numbers) {
            if (num % 2 == 0) {
                hasEven = true;
                break;
            }
        }
        System.out.println("Has even (enhanced for loop): " + hasEven);
    }
}
  

5. Determine if All Elements Have a Particular Property

Check if All Elements are Positive

public class ArrayAllPositive {
    public static void main(String[] args) {
        int[] numbers = {3, 5, 1, 7, 9};
        boolean allPositive = true;

        // Using for loop
        for (int i = 0; i < numbers.length; i++) {
            if (numbers[i] <= 0) {
                allPositive = false;
                break;
            }
        }
        System.out.println("All positive (for loop): " + allPositive);

        // Using enhanced for loop
        allPositive = true;
        for (int num : numbers) {
            if (num <= 0) {
                allPositive = false;
                break;
            }
        }
        System.out.println("All positive (enhanced for loop): " + allPositive);
    }
}
  

6. Access All Consecutive Pairs of Elements

public class ConsecutivePairs {
    public static void main(String[] args) {
        int[] numbers = {3, 5, 1, 7, 9};

        // Using for loop
        for (int i = 0; i < numbers.length - 1; i++) {
            System.out.println("Pair: " + numbers[i] + ", " + numbers[i + 1]);
        }

        // Enhanced for loop is not ideal for this task because it does not provide access to indices.
    }
}
  

7. Determine the Presence or Absence of Duplicate Elements

public class DuplicateCheck {
    public static void main(String[] args) {
        int[] numbers = {3, 5, 1, 7, 9};
        boolean hasDuplicate = false;

        // Using for loop
        for (int i = 0; i < numbers.length; i++) {
            for (int j = i + 1; j < numbers.length; j++) {
                if (numbers[i] == numbers[j]) {
                    hasDuplicate = true;
                    break;
                }
            }
            if (hasDuplicate) break;
        }
        System.out.println("Has duplicate (for loop): " + hasDuplicate);

        // Enhanced for loop is not ideal for this task due to the need for two indices.
    }
}
  

8. Determine the Number of Elements Meeting Specific Criteria

Count Odd Numbers

public class CountOddNumbers {
    public static void main(String[] args) {
        int[] numbers = {3, 5, 1, 7, 9};
        int oddCount = 0;

        // Using for loop
        for (int i = 0; i < numbers.length; i++) {
            if (numbers[i] % 2 != 0) {
                oddCount++;
            }
        }
        System.out.println("Odd count (for loop): " + oddCount);

        // Using enhanced for loop
        oddCount = 0;
        for (int num : numbers) {
            if (num % 2 != 0) {
                oddCount++;
            }
        }
        System.out.println("Odd count (enhanced for loop): " + oddCount);
    }
}
  

9. Shift or Rotate Elements Left or Right

Shift Elements Left by One Position

import java.util.Arrays;

public class ShiftLeft {
    public static void main(String[] args) {
        int[] numbers = {3, 5, 1, 7, 9};

        // Using for loop
        int first = numbers[0];
        for (int i = 0; i < numbers.length - 1; i++) {
            numbers[i] = numbers[i + 1];
        }
        numbers[numbers.length - 1] = first;

        System.out.println("Shifted left (for loop): " + Arrays.toString(numbers));
    }
}
  

Shift Elements Right by One Position

import java.util.Arrays;

public class ShiftRight {
    public static void main(String[] args) {
        int[] numbers = {3, 5, 1, 7, 9};

        // Save the last element since it will wrap around to the front
        int last = numbers[numbers.length - 1];

        // Shift each element to the right by 1 position
        for (int i = numbers.length - 1; i > 0; i--) {
            numbers[i] = numbers[i - 1];
        }

        // Place the last element in the first position
        numbers[0] = last;

        System.out.println("Shifted right by 1: " + Arrays.toString(numbers));
    }
}
  

10. Reverse the Order of the Elements

1. Using a Two-Pointer Technique

import java.util.Arrays;

public class ReverseArray {
    public static void main(String[] args) {
        int[] numbers = {3, 5, 1, 7, 9};

        for (int i = 0; i < numbers.length / 2; i++) {
            int temp = numbers[i];
            numbers[i] = numbers[numbers.length - 1 - i];
            numbers[numbers.length - 1 - i] = temp;
        }
        System.out.println("Reversed (for loop): " + Arrays.toString(numbers));
    }
}
  

2. Using an Auxiliary Array

import java.util.Arrays;

public class ReverseArray {
    public static void main(String[] args) {
    
        int[] numbers2 = {3, 5, 1, 7};
        // Create a new array
        int[] reversed = new int[numbers2.length];

        for (int i = 0; i < numbers2.length; i++) {
            reversed[i] = numbers2[numbers2.length - 1 - i];
        }

        System.out.println("Reversed array: " + Arrays.toString(reversed));
    }
}
  

加分Project

点这里查看详情

从AP Classroom 中选一个已经做过的 FRQ,写出可执行代码,在blueJay中成功运行,具体要求和评分标准如下:


FRQ Coding Project Rubric / FRQ 编程项目评分标准

Grade Guidelines Criteria
A+ (9-10) Exceptional work. Shows clear understanding and full mastery of the problem, and code is executed flawlessly.
出色的作品。展现了对问题的深入理解和完整掌握,代码运行无误。
  • Code is 100% correct for all test cases, including edge cases.
    代码对所有测试用例(包括边界情况)均完全正确。
  • Code is well-structured, clean, and highly readable with clear variable and method names.
    代码结构清晰,整洁,且具备高度可读性,变量和方法命名合理。
  • Detailed comments explaining purpose, logic, and major steps.
    提供详细注释,解释代码目的、逻辑和主要步骤。
  • Creative enhancements or extra features beyond the requirements (if any).
    增加了创新性改进或额外功能(如有)。
  • No detectable AI patterns (e.g., overly generic, verbose comments).
    无明显 AI 痕迹(如过于通用或冗长的注释)。
A (8) Excellent work. Code is accurate and runs without errors, with some minor style or completeness issues.
优秀作品。代码正确,运行无误,只有些微样式或完整性问题。
  • Code produces correct output for most test cases, with minor issues in one or two edge cases.
    代码对大部分测试用例产生正确输出,少数边界情况可能有小问题。
  • Good structure and readability with mostly clear variable/method names.
    代码结构合理且可读性高,变量/方法命名清晰。
  • Includes appropriate comments that clarify the code.
    包含适当的注释,能够帮助理解代码。
  • Efficiently coded with minimal redundancy.
    代码高效,冗余最小化。
  • Little evidence of AI assistance.
    几乎没有 AI 协助的痕迹。
A- (7) Strong work, but may have minor flaws in logic or structure. Code generally runs well.
表现良好,但在逻辑或结构上有小瑕疵。代码整体运行正常。
  • Code produces mostly correct results, with issues only in a few cases.
    代码在大部分情况下输出正确,少数情况可能有问题。
  • Readable and organized structure, though may have minor issues in clarity.
    代码结构清晰有序,但清晰度可能略有不足。
  • Includes some comments, but they may lack detail.
    包含一些注释,但细节不足。
  • Code is mostly efficient, with minor inefficiencies.
    代码基本高效,少量低效部分。
  • Minimal indicators of AI involvement.
    几乎没有 AI 参与的迹象。
B+ (6) Good effort with noticeable flaws. Code runs, but may have errors or inefficiencies.
有明显缺陷的良好尝试。代码可以运行,但可能有错误或低效部分。
  • Code produces correct output for main cases, but fails on some edge cases.
    代码在主要情况中输出正确,但在某些边界情况中失败。
  • Structure is mostly clear, but some parts are hard to follow.
    代码结构大部分清晰,但部分难以理解。
  • Basic comments are provided, but lacking detail or clarity.
    有基本注释,但缺乏细节或清晰性。
  • Some inefficiencies or redundant code present.
    存在部分低效或冗余代码。
  • Some signs of AI involvement may be noticeable.
    可能有明显的 AI 痕迹。
B (5) Satisfactory but needs improvement. Code has a mix of correct and incorrect results.
基本合格,但需改进。代码结果有正确和错误混合。
  • Code produces partially correct output, but fails on a significant number of cases.
    代码输出部分正确,但在许多情况中失败。
  • Structure is inconsistent or hard to follow.
    结构不一致,难以理解。
  • Few comments, and they don’t explain the logic well.
    注释少,且不能很好地解释逻辑。
  • Several redundancies or inefficient methods are present.
    存在多处冗余或低效代码。
  • Noticeable AI-generated patterns in style, structure, or comments.
    在样式、结构或注释中有明显的 AI 痕迹。
B- (4) Acceptable, but with significant issues in execution, structure, or clarity.
可接受,但在执行、结构或清晰度上有重大问题。
  • Code produces partially correct output, with frequent errors or failures.
    代码输出部分正确,但经常出错或失败。
  • Messy or unclear structure; difficult to read.
    结构混乱或不清晰,难以阅读。
  • Lacks comments, or comments are unhelpful.
    缺少注释,或注释无用。
  • Code shows significant inefficiencies.
    代码存在明显的低效部分。
  • Code appears potentially AI-assisted with unusual language or generic comments.
    代码可能有 AI 痕迹,例如语言不自然或使用通用注释。
C+ (3) Limited success. Code runs but with minimal correctness, clarity, or efficiency.
成功有限。代码运行,但正确性、清晰度或效率低。
  • Code produces incorrect results for most cases, with only minor correct output.
    代码在大多数情况下不正确,仅少量输出正确。
  • Poor structure and readability.
    结构和可读性差。
  • Little to no comments explaining the code.
    几乎没有解释代码的注释。
  • Code is highly inefficient and appears rushed.
    代码低效且草率。
  • Clear indications of AI-generated code (e.g., unnatural explanations or syntax).
    有明显的 AI 痕迹(例如不自然的解释或语法)。
C (2) Minimal success. Code compiles, but has many issues in logic and readability.
成功极少。代码可以编译,但逻辑和可读性有很多问题。
  • Code barely compiles but fails in almost all cases.
    代码勉强编译,但几乎所有情况都失败。
  • Structure is chaotic and unclear.
    结构混乱且不清晰。
  • No comments or explanations.
    没有注释或解释。
  • Severely inefficient or redundant methods.
    存在极度低效或冗余的方法。
  • Highly probable AI patterns; further investigation warranted.
    明显的 AI 痕迹;需要进一步调查。
C- (1) Very limited or incomplete. Code is far from functional and poorly constructed.
极其有限或不完整。代码几乎无法正常运行且结构糟糕。
  • Code does not compile or crashes immediately.
    代码无法编译或立即崩溃。
  • Unreadable structure and no logic in place.
    结构无法阅读,缺乏逻辑。
  • No comments.
    没有注释。
  • Not executable or far from correct.
    无法运行或远非正确。
  • Appears to be copied or heavily AI-generated without understanding.
    疑似复制或大量 AI 生成,没有理解。

Ask for Reflection / 提交时可能问你的问题:


Core Concepts:
核心知识点


Java Class Sample:

//This is a Cat class. It is like a blueprint for making Cat objects.
// A class defines the characteristics(color and breed) and actions(meowing) of the objects.
public class Cat{
    //Characteristics of the Cat class
    //instance variables 
    private String color;
    private String breed;
    private int age;
    private boolean isHungry;
    private String name;
    private double weight;
    private double height;
    
    // Default Constructor
    public Cat(){
        //This is a constructor. It is used to create a Cat object
        //with some default values.
        color = "unkown";
        breed = "unkown";
        age = 0;
        isHungry = true;
    }
    
    // Constructor with parameters
    public Cat(int a){
        age = a;
        
    }
    
    public Cat(int a, String c){
        age = a;
        color = c;
    }
    
    public Cat(String c, int a){
        color = c;
        age = a;
    }
    
    // Methods
    public void showAge(){
        System.out.println("Age: " + age);
    }
    
    
    public void meow(){
        System.out.println("Meow!!!");
        
    } 
    
    public void eat(int foodAmount){
        System.out.println("I eat " + foodAmount + " a day");
        
    }
    
    // Main method
    public static void main(String[] args){
        //int num = 2;
        //System.out.println("num: " + num);
        //int num2 = num;
        //System.out.println("num2: " + num2);
        //num = 9; //changing num later does not affect num2
        //System.out.println("num2 after num change: " + num2);
        //System.out.println("num after num change: " + num);
        Cat littleCat = new Cat(20, "black");
        //System.out.println("littleCat's color: " + littleCat.color);
        Cat bigCat = littleCat;
        //System.out.println("bigCat's color: " + bigCat.color);
        littleCat.color = "pink";
        //bigCat.showAge();
        bigCat.eat(50);
        //System.out.println("littleCat's color after change: " + littleCat.color);
        //System.out.println("bigCat's color after change littleCat: " + bigCat.color);
    }
    
    
}