# data[].attributes.body
public static void main(String[] args) {

ArrayList<SparseArrayEntry> arrayList = new ArrayList<SparseArrayEntry>();
arrayList.add(new SparseArrayEntry(2, 0, 1));
arrayList.add(new SparseArrayEntry(1, 1, 5));
arrayList.add(new SparseArrayEntry(3, 1, -9));
arrayList.add(new SparseArrayEntry(1, 4, 4));
SparseArray arr = new SparseArray(6, 5, arrayList);
System.out.println("The original array:");
System.out.println(arr);
arr.removeColumn(1);
System.out.println("New array is:");
System.out.println(arr);
}

# data[].attributes.attachment_link.readable_text
1부터 입력한 정수까지 1씩 증가시켜 출력하는 프로그램을 작성하되,
3의 배수인 경우는 출력하지 않도록 만들어보자.

예를 들면,
1 2 4 5 7 8 10 11 13 14 ...
와 같이 출력하는 것이다.

참고
반복문 안에서 continue;가 실행되면 그 아래의 내용을 건너뛰고, 다음 반복을 수행한다.
즉, 다음 반복으로 넘어가는 것이다.

예시
for(i=1; i<=n; i++) //1부터 시작해 n까지 1씩 증가시키면서 반복한다.
{
if(i%2==0)
continue; //짝수라면? 아래 부분은 건너뛰고! 계속~
printf("%d ", i); //결국 짝수가 아닐 때에만 출력된다.
}

# data[].attributes.attachment_link.title
[기초-종합] 3의 배수는 통과?(설명)

# data[].attributes.attachment_link.description
1부터 입력한 정수까지 1씩 증가시켜 출력하는 프로그램을 작성하되, 3의 배수인 경우는 출력하지 않도록 만들어보자. 예를 들면, 1 2 4 5 7 8 10 11 13 14 ... 와 같이 출력하는 것이다. 참고 반복문 안에서 continue;가 실행되면 그 아래의 내용을 건너뛰고, 다음 반복을 수행한다. 즉, 다음 반복으로 넘어가는 것이다.

# data[].attributes.attachment_link.description
코드업 - 3의 배수의 합

# data[].attributes.attachment_link.title
홀수는 더하고 짝수는 빼고 1

# data[].attributes.attachment_link.description
코드업 - 홀수는 더하고 짝수는 빼고 1

# data[].attributes.attachment_link.title
[기초-종합] 짝수 합 구하기(설명)

# data[].attributes.attachment_link.description
코드업 - [기초-종합] 짝수 합 구하기(설명)

# data[].attributes.attachment_link.description
코드업 - k 제곱 구하기

# data[].attributes.attachment_link.description
코드업 - 최대값 구하기

# data[].attributes.attachment_link.description
코드업 - 터널 통과하기 1

# data[].attributes.attachment_link.readable_text
1, 2, 3 ... 을 순서대로 계속 더해나갈 때,
그 합이 입력한 정수보다 작을 동안만 계속 더하는 프로그램을 작성해보자.

즉, 1부터 n까지 정수를 계속 더한다고 할 때,
어디까지 더해야 입력한 수보다 같거나 커지는지 알아보고자 하는 문제이다.

하지만, 이번에는 그 때의 합을 출력해야 한다.

예를 들어 57을 입력하면
1+2+3+...+8+9+10=55에 다시 11을 더해 66이 될 때,
그 값 66이 출력되어야 한다.

참고
조건문이나 반복문의 코드블록 안에서 break;가 실행되면
가장 가까운 반복 코드블록 구역의 밖으로 빠져나간다.

예시
int n, i, s=0;
scanf("%d", &n);
for(i=1; ; i++) //for 반목문에서 가운데의 조건이 빠진 경우 무한 반복된다.
{
s+=i;
if(s>=n)
break; //참이면, 가장 가까운 반복 코드블록의 밖으로 빠져나간다.
} //break; 가 실행되면 반복을 중단하고 여기로 빠져 나온다.
printf("%d", s);

무한 반복이 되는 코드는
while(1) {...}, do {...}while(1); 등도 가능하다.
0이 아니면 모두 참(true)으로 인식되기 때문이다.

# data[].attributes.attachment_link.title
[기초-종합] 여기까지! 이제 그만~(설명)

# data[].attributes.attachment_link.description
코드업 - [기초-종합] 여기까지! 이제 그만~(설명)

# data[].attributes.attachment_link.description
코드업 - 최대값 구하기

# data[].attributes.attachment_link.readable_text
태어난 해, 월, 일을 입력받아 사주팔자를 보는 프로그램을 작성하시오.

사주를 보는 방법)

세 수(년,월,일)가 주어지면,  (년 - 월 + 일)에 마지막 숫자가 0이면 "대박"을 출력, 그렇지 않으면 "그럭저럭"을 출력하세요.

# data[].attributes.attachment_link.title
당신의 사주를 봐 드립니다 1

# data[].attributes.attachment_link.description
코드업 - 당신의 사주를 봐 드립니다 1

# data[].attributes.attachment_link.title
홀수는 더하고 짝수는 빼고 1

# data[].attributes.attachment_link.description
코드업 - 홀수는 더하고 짝수는 빼고 1

# data[].attributes.attachment_link.readable_text
이번에 또 도둑이 들었다. 도둑으로 판단되는 용의자를 10명을 검거하였다.

CCTV를 정밀 분석한 결과 도둑은 검거한 10명 중 키가 3번째로 크다는 사실을 알았다.

10명의 키를 조사하여 도둑을 검거하는 프로그램을 작성하시오. (단, 입력되는 모든 키는 서로 다르다.)

# data[].attributes.attachment_link.description
코드업 - 범인을 잡아라 2

# data[].attributes.attachment_link.readable_text
대영이는 SNS를 이용한 컨설팅 회사를 운영하고 있다.

이 회사에서 획기적인 기획안을 개발하여 사람들에게 홍보를 하려고 한다.

홍보를 할 경우 수입과 그렇지 않을 경우의 수입을 알고 있을 경우,

홍보를 하는 경우가 유리한가?

홍보를 하지 않은 경우가 유리한가?

그것도 아니면 홍보를 하든 안하든 별 관계가 없는가?

이것을 알아내는 프로그램을 만드시오.

# data[].attributes.attachment_link.description
코드업 - 컨설팅 회사

# data[].attributes.attachment_link.title
n개의 수 중 5의 배수의 합

# data[].attributes.attachment_link.description
코드업 - n개의 수 중 5의 배수의 합

# data[].attributes.attachment_link.readable_text
당신은 강의 상태를 결정하기 위해 매우 긴 강에서 산도 레벨 수치를 수집하고 있습니다.

강에는 N(2 ≤ N ≤ 2 000 000)개의 센서가 있고, 각 센서는 정수 수치 R(1 ≤ R ≤ 1 000)을 사용합니다.

당신은 연구의 목적으로 각 수치의 빈도를 알고 싶어합니다. 그리고 두개의 빈도가 가장 높은 수치 사이의 절대 차를 구하려고 합니다.

만약 가장 빈도가 높은 수치가 두개 이상이면, 그 차이 계산이 빈도가 높은 두 수치의 최대 절대 차이어야 합니다.

보충 설명)

예를 들어, 센서의 개수가 5개이고, 1 1 1 4 3 이라면

빈도가 가장 높은 센서는 1이고(3회), 두 번째로 높은 빈도는 4와 3인데 빈도 수치의 최대 절대 차가 되려면 4를 선택해야 한다.

따라서 4 - 1 = 3 이된다.

한마디로 빈도가 높은 두 센서를 찾아서 차를 구하되 차이가 최대가 되게 하는 문제입니다.

# data[].attributes.attachment_link.description
당신은 강의 상태를 결정하기 위해 매우 긴 강에서 산도 레벨 수치를 수집하고 있습니다. 강에는 N(2 ≤ N ≤ 2 000 000)개의 센서가 있고, 각 센서는 정수 수치 R(1 ≤ R ≤ 1 000)을 사용합니다. 당신은 연구의 목적으로 각 수치의 빈도를 알고 싶어합니다. 그리고 두개의 빈도가 가장 높은 수치 사이의 절대 차를 구하려고 합니다.

# data[].attributes.attachment_link.readable_text
알바왕 비버가 한라봉 상자 포장 아르바이트를 한다.
상자의 크기는 용량에 따라 4종류(1kg, 3kg, 5kg, 10kg)로 나뉘는데, 반드시 상자의 용량만큼 한라봉을 담아야 한다.
즉, 상자의 용량보다 부족하거나 초과하여 한라봉을 담을 수 없다.
또한, 상자를 최소한으로 사용해서 한라봉을 포장해야 한다.
예를 들어, 3kg의 한라봉을 포장하기 위해서는 1kg 상자 3개가 아닌, 3kg 상자 1개를 사용해야 한다.

비버가 n kg의 한라봉을 모두 포장하려면, 최소 몇 개의 상자가 필요할까?

# data[].attributes.attachment_link.description
알바왕 비버가 한라봉 상자 포장 아르바이트를 한다. 상자의 크기는 용량에 따라 4종류(1kg, 3kg, 5kg, 10kg)로 나뉘는데, 반드시 상자의 용량만큼 한라봉을 담아야 한다. 즉, 상자의 용량보다 부족하거나 초과하여 한라봉을 담을 수 없다. 또한, 상자를 최소한으로 사용해서 한라봉을 포장해야 한다. 예를 들어, 3kg의 한라봉을 포장하기 위해서는 1kg 상자 3개가 아닌, 3kg 상자 1개를 사용해야 한다.

# data[].attributes.headline
배열로 10칸 만들어서 

# data[].attributes.body
배열로 10칸 만들어서
4
6
2
8
0
5
1
7
9
3

이 숫자가 거꾸로 출력되게 하기

# data[].attributes.headline
10개의 정수를 입력받아 가장 큰 수 반환하기

# data[].attributes.subject
10개의 정수를 입력받아 가장 큰 수 반환하기

# data[].attributes.attachment_link.readable_text
이번에 또 도둑이 들었다. 도둑으로 판단되는 용의자를 10명을 검거하였다.

CCTV를 정밀 분석한 결과 도둑은 검거한 10명 중 키가 3번째로 크다는 사실을 알았다.

10명의 키를 조사하여 도둑을 검거하는 프로그램을 작성하시오. (단, 입력되는 모든 키는 서로 다르다.)

# data[].attributes.attachment_link.description
코드업 - 범인을 잡아라 2

# data[].attributes.attachment_link.readable_text
These problems are easier than most of those that you will usually see on the AP CS A exam.

2

The size of outer array is the number of rows. Remember that two-dimensional arrays are actually an array of arrays in Java.

4

The size of the inner array is the number of columns.

8

This is the total number of items in the array.

You can see how the array looks by clicking on the following Ex-9-7-1.

8-7-2: Which of the following statements assigns the letter S to the third row and first column of a two-dimensional array named (assuming row-major order).

strGrid[0][2] = "S";

The code letterGrid[0][2] = "S"; actually sets the 1st row and 3rd column to hold a reference to the String object "S".

strGrid[1][3] = "S";

This would be true if row and column indicies started at 1 instead of 0 and if this was in column major order.

strGrid[3][1] = "S";

This would be true if row and column indicies started at 1 instead of 0.

strGrid[2][0] = "S";

In row-major order the row is specified first followed by the column. Row and column indicies start with 0. So letterGrid[2][0] is the 3rd row and 1st column.

strGrid[0][0] = "S";

This would set the element at the first row and column.

a[0][3]

This would be true if the row index started at 0, but the column index started at 1.

a[1][3]

Both the row and column indicies start with 0.

a[0][2]

The value 6 is at row 0 and column 2.

a[2][0]

The row index is specified first, then the column index.

a[3][1]

The row index is specified first and the indicies start at 0.

You have attempted of activities on this page

# data[].attributes.attachment_link.title
8.7.1. Easier Multiple Choice Questions - AP CSAwesome

# data[].attributes.attachment_link.description
These problems are easier than most of those that you will usually see on the AP CS A exam. 2 The size of outer array is the number of rows. Remember that two-dimensional arrays are actually an array of arrays in Java. 4 The size of the inner array is the number of columns.

# data[].attributes.body
public class GrayImageTester {
public static void main (String[] args)
{
int [][] p={{255,184,178,84,129},{84,255,255,130,84},{78,255,0,0,78},{84,130,255,130,84}};
int [][] p2={{221,184,178,84,135},{84,255,255,130,84},{78,255,0,0,78},{84,130,255,130,84}};
int [][] p3={{221,184,100,84,135},{0,125,171,130,84},{78,255,0,0,78},{84,130,255,130,84}};
GrayImage pic=new GrayImage(p);
GrayImage pic2=new GrayImage(p2);
GrayImage pic3=new GrayImage(p3);
System.out.println("Part A");
System.out.println(pic+"\ncountWhitePixels() should return 5");
System.out.println("your code returns "+pic.countWhitePixels());
System.out.println("Part B");
System.out.println("processImage() should change \n"+pic2+"\n into \n"+pic3);
pic2.processImage();
System.out.println("your code produces\n"+pic2);
}
}

# data[].attributes.body
public class GrayImage {
public static final int BLACK=0;
public static final int WHITE=255;

private int[][] pixelValues;

public int countWhitePixels()
{
//a문제
}

public void processImage()
{
//b문제

}
public GrayImage(int[][] p)
{
pixelValues=p;
}
public String toString(){
int rows=pixelValues.length;
int cols=pixelValues[0].length;
String[] s=new String[rows];
for(int r=0;r<rows;r++){
s[r]=String.format(" %2d",r);
for (int c=0; c<cols;c++)
s[r]=s[r]+String.format("[%3d]",pixelValues[r][c]);
}
String result="  ";
for (int c=0;c<cols;c++)
result+=String.format("%5d", c);
for (int r=0;r<rows;r++)
result+="\n"+s[r];
return result;
}
}

# data[].attributes.body
import java.util.Arrays;

public class DiverseArray {

public static void main(String[] args) {

int[] arr1 = { 1, 3, 2, 7, 3 };
System.out.println(Arrays.toString(arr1)+": ArraySum = "+arraySum(arr1));

int[][] arr2 = {
{1, 3, 2, 7, 3},
{10,10,4,6,2},
{5,3,5,9,6},
{7,6,4,2,1}
};

for ( int[] tt : arr2) {
System.out.println(Arrays.toString(tt));
}
System.out.println(": RowSum = "+Arrays.toString( rowSums(arr2) ) );

int[][] arr3 = {
{1, 1, 5, 3, 4},
{12, 7, 6, 1, 9},
{8, 11, 10, 2, 5},
{3, 2, 3, 0, 6}
};

if (isDiverse(arr2)) {
System.out.println("arr2 is diverse");
} else {
System.out.println("arr2 is NOT diverse");
}

if (isDiverse(arr3)) {
System.out.println("arr3 is diverse");
} else {
System.out.println("arr3 is NOT diverse");
}
/*
if (isDiverse(arr2)) System.out.println("arr2 is diverse");
else System.out.println("arr2 is NOT diverse");
if (isDiverse(arr3)) System.out.println("arr3 is diverse");
else System.out.println("arr3 is NOT diverse");
*/

}

// complete the following code!!
public static int arraySum(int[] arr){

}

// complete the following code!!
public static int[] rowSums(int[][] arr){

}

// complete the following code!!
public static boolean isDiverse(int[][] arr2D){

}

}

# data[].attributes.attachment_link.readable_text
These problems are easier than most of those that you will usually see on the AP CSA exam.

7-11-1-5: Which of the following is the correct way to set the second value in a list called to 5?

nums[1] = 5;

This is how you set the second value in an array, but not in a list.

nums[2] = 5;

This is how you set the third value in an array, but not in a list.

nums.set(5, 1);

This would the value at index 5 to 1.

nums.set(1, 5);

This sets the second value in the list to 5.

nums.set(2, 5);

This would set the third value in the list to 5. Remember that the first value is at index 0.

7-11-1-6: Which of the following is the correct way to remove the value 3 from the list ?

nums.remove(3);

This would remove the value at index 3 which is 1.

nums.remove(0);

This would remove the value at index 0 which is 5.

nums.remove(1);

This would remove the value at index 1 which is 3.

nums.remove(2);

This would remove the value at index 2 which is 2.

7-11-1-7: Which of the following is the correct way to add 2 between the 1 and 3 in the following list ?

nums.add(2, 0);

This would add 0 at index 2. Remember that the method is add(index, obj).

nums.add(2, 1);

This would add 1 at index 2. Remember that the method is add(index, obj)

nums.add(0, 2);

This would add 2 at index 0 which would result in [2, 1, 3, 4]

nums.add(1, 2);

This would add 2 at index 1 which would result in [1, 2, 3, 4]

nums.add(2, 2);

This would add 2 at index 2 which would result in [1, 3, 2, 4]

You can step through the code above by clicking on the following Ex-8-11-9.

You can step through the code above by clicking on the following Ex-8-11-10.

You have attempted of activities on this page

# data[].attributes.attachment_link.title
7.13.1. Easier Multiple Choice Questions - AP CSAwesome

# data[].attributes.attachment_link.description
These problems are easier than most of those that you will usually see on the AP CSA exam. 7-11-1-5: Which of the following is the correct way to set the second value in a list called to 5? nums[1] = 5; This is how you set the second value in an array, but not in a list.

# data[].attributes.attachment_link.readable_text
These problems are like those you will see on the AP CS A exam.

You can step through the code above by clicking on this link Example-8-12-1.

You can step through the code above by clicking on this link Example-8-12-2.

You can step through the code above by clicking on the link Example-8-12-3.

You can step through the code above by clicking on the link Example-8-12-4.

You can step through the code above by clicking on the link Example-8-12-5.

You can step through the code above by clicking on the link Example-8-12-6.

[2, 3, 4, 5]

This would be true if it removed the first 4 but it removes the value at index 4.

[2, 3, 5]

This would be true if it removed all the 4 values, but it removes the value at index 4.

[4, 2, 3, 5]

This would be true if it removed the value at index 3.

[4, 2, 3, 4]

This removes the value at index 4 which is 5.

You can step through the code above by clicking on the following Example-8-12-7.

You can step through the code above by clicking on the following Example-8-12-8.

You can step through the code above by clicking on the following Example-8-12-9.

You can step through the code above by clicking on the following Example-8-12-10.

# data[].attributes.attachment_link.title
7.11.2. Medium Multiple Choice Questions - AP CSAwesome

# data[].attributes.attachment_link.description
These problems are like those you will see on the AP CS A exam. You can step through the code above by clicking on this link Example-8-12-1. You can step through the code above by clicking on this link Example-8-12-2. You can step through the code above by clicking on the link Example-8-12-3.

# data[].attributes.attachment_link.readable_text
These problems are about the same or harder than those you will see on the AP CS A exam.

7-11-3-1: What is in the list if it initially contained {5, 3, 1} and the following code is executed?

[5, 3, 1, 6]

The remove(1) removes the item at index 1 which will be 5 after the 4 is added at index 0.

[4, 3, 1, 6]

The add(6) adds the 6 at the end of the list. The add(0,4) will add 4 at index 0. The remove(1) removes the 5 at index 1.

[4, 3, 6]

The remove(1) doesn't remove the 1, it removes the value at index 1.

[5, 3, 6]

The 5 will be removed with the remove(1).

[4, 5, 3, 6]

This would be true if remove(1) removed the item with that value, but it removes the item at that index.

You can step through the code above by clicking on the following Example-8-13-1.

7-11-3-2: Assume that nums has been created as an ArrayList object and initially contains the following Integer values: [0, 0, 4, 2, 5, 0, 3, 0]. What will nums contain as a result of executing the following method numQuest?

[0, 0, 4, 2, 5, 0, 3, 0]

This shows the original values but this code does remove some zeros so this can't be right.

[3, 5, 2, 4, 0, 0, 0, 0]

This shows all zeros at the end, but this code removes 0's so this can't be right.

[0, 0, 0, 0, 4, 2, 5, 3]

This shows all zeros at the beginning, but this code removes zeros so this can't be right.

[4, 2, 5, 3]

This shows all zeros removed. This would be correct if k was only incremented if a value wasn't removed.

[0, 4, 2, 5, 3]

This code will loop through the array list and if the current value at the current index (k) is 0, it will remove it. When you remove a value from an array list, it moves all values to the right of that down one. So the first 0 will be deleted but the second one will not since k is incremented even if you remove something. You should only increment k if you didn't remove something and then you would remove all 0's from the list.

You can step through the code above by clicking on the following Example-8-13-2.

For more practice with free response questions with Lists, look up the following FRQs in this FRQs spreadsheet:

# data[].attributes.attachment_link.title
7.11.3. Hard Multiple Choice Questions - AP CSAwesome

# data[].attributes.attachment_link.description
These problems are about the same or harder than those you will see on the AP CS A exam. 7-11-3-1: What is in the list if it initially contained {5, 3, 1} and the following code is executed? [5, 3, 1, 6] The remove(1) removes the item at index 1 which will be 5 after the 4 is added at index 0.

# data[].attributes.body
public class CookieMain {

public static void main(String[] args) {

MasterOrder goodies = new MasterOrder();
goodies.addOrder(new CookieOrder("Chocolate Chip", 1));
goodies.addOrder(new CookieOrder("Shortbread", 5));
goodies.addOrder(new CookieOrder("Macaroon", 2));
goodies.addOrder(new CookieOrder("Chocolate Chip", 3));

goodies.print();
// (a)  - should get 11
System.out.println("Total number of cookie boxes: "+goodies.getTotalBoxes());

// (b) -
String toRemove = "Chocolate Chip";
System.out.println("===========\nAfter Removal of \""+toRemove+"\" : " + goodies.removeVariety(toRemove));
goodies.removeVariety(toRemove);
goodies.print();

}

}

# data[].attributes.body
import java.util.ArrayList;
import java.util.List;

public class MasterOrder {

private List<CookieOrder> orders;

public MasterOrder()
{
orders = new ArrayList<CookieOrder>();
}

public void addOrder(CookieOrder theOrder)
{
orders.add(theOrder);
}

public int getTotalBoxes(){

}

public int removeVariety(String cookieVar) {

}

public void print() {
System.out.println("----------------");
for(int i=0; i<orders.size(); i++) {
System.out.println(orders.get(i).getVariety()+": "+orders.get(i).getNumBoxes());
}
System.out.println("----------------");
}
}

# data[].attributes.body
public class CookieOrder {

private String type;
private int num;

public CookieOrder(String variety, int numBoxes){
type = variety;
num = numBoxes;
}

public String getVariety(){
return type;
}

public int getNumBoxes(){
return num;
}

}

# data[].attributes.body
public class Sum
{
public static void main(String[] args)
{
int[][] array = {{4, 4, 5, 6, 3, 1},
{14, 2, 5, 4, 8, 2},
{45, 12, 13, 5, 2, 1}};

}

// Returns the sum of row row in 2D array array
public static int sumRow(int[][] array, int row)
{

}

// Returns the sum of all elements in array
public static int sumArray(int[][] array)
{

}
}

# data[].attributes.attachment_link.readable_text
Given two strings, a and b, return the result of putting them together in the order abba, e.g. "Hi" and "Bye" returns "HiByeByeHi".

makeAbba("Hi", "Bye") → "HiByeByeHi"
makeAbba("Yo", "Alice") → "YoAliceAliceYo"
makeAbba("What", "Up") → "WhatUpUpWhat"
Go...Save, Compile, Run (ctrl-enter) Show Hint

# data[].attributes.attachment_link.description
Given two strings, a and b, return the result of putting them together in the order abba, e.g. “Hi” and “Bye” returns “HiByeByeHi”.

# data[].attributes.attachment_link.description
Given a string, return the string made of its first two chars, so the String “Hello” yields “He”. If the string is shorter than length 2, return whatever there is, so “X” yields “X”, and the empty string ”″ yields the empty string ”″. Note that str.length() returns the length of a string.

# data[].attributes.attachment_link.description
Given a string of even length, return a string made of the middle two chars, so the string "string" yields "ri". The string length will be at least 2.

# data[].attributes.attachment_link.readable_text
Given a string and an int n, return a string made of n repetitions of the last n characters of the string. You may assume that n is between 0 and the length of the string, inclusive.

repeatEnd("Hello", 3) → "llollollo"
repeatEnd("Hello", 2) → "lolo"
repeatEnd("Hello", 1) → "o"
Go...Save, Compile, Run (ctrl-enter)

# data[].attributes.attachment_link.description
Given a string and an int n, return a string made of n repetitions of the last n characters of the string. You may assume that n is between 0 and the length of the string, inclusive.

# data[].attributes.attachment_link.readable_text
Given two strings, word and a separator sep, return a big string made of count occurrences of the word, separated by the separator string.

repeatSeparator("Word", "X", 3) → "WordXWordXWord"
repeatSeparator("This", "And", 2) → "ThisAndThis"
repeatSeparator("This", "And", 1) → "This"
Go...Save, Compile, Run (ctrl-enter)

# data[].attributes.attachment_link.description
Given two strings, word and a separator sep, return a big string made of count occurrences of the word, separated by the separator string. repeatSeparator("Word", "X", 3) → "WordXWordXWord"repeatSeparator("This", "And", 2) → "ThisAndThis"repeatSeparator("This", "And", 1) → "This" Go...Save, Compile, Run (ctrl-enter)

# data[].attributes.attachment_link.readable_text
If you have multiple subclasses that inherit from a superclass, you can form an inheritance hierarchy. Every subclass is-a or is a kind of the superclass. For example, here is an inheritance hierarchy of Shapes. Square is-a Rectangle and a subclass of Rectangle. Rectangle is-a Shape and a subclass of Shape. In Java, the class Object is at the top of hierarchy. Every class in Java inherits from Object and is-an Object.

¶

One of the main reasons to use an inheritance hierarchy is that the instance variables and methods from a superclass are inherited and can be used in a subclass without rewriting or copying code.

9-5-1: What variables and methods might be inherited from the superclass Shape in the inheritance hierarchy above?

9-5-2: Can you make a 3 level inheritance hierarchy for living things on Earth?

9.5.1. Superclass References

A superclass reference variable can hold an object of that superclass or of any of its subclasses. For example, a Shape reference variable can hold a Rectangle or Square object. (This is a type of polymorphism which will be defined in the next lesson).

// The variables declared of type Shape can hold objects of its subclasses
Shape s1 = new Shape ();
Shape s2 = new Rectangle ();
Shape s3 = new Square ();

Notice that the opposite is not true. You cannot declare a variable of the subclass and put in a superclass object. For example, a Square reference cannot hold a Shape object because not all Shapes are Squares. The code below will give an "Incompatible types: Shape cannot be converted to Square" error (although you could use a type-cast to get it to be a (Square)).

// A subclass variable cannot hold the superclass object!
// A Square is-a Shape, but not all Shapes are Squares.
// Square q = new Shape(); // ERROR!!

Why is using a superclass reference for subclass objects useful? Because now, we can write methods with parameters of type Shape or have arrays of type Shape and use them with any of its subclasses as seen in the next sections.

Check your understanding

9-5-3: A class Student inherits from the superclass Person. Which of the following assignment statements will give a compiler error?

Person p = new Person();

This declares and creates an object of the same class Person.

Person p = new Student();

This is allowed because a Student is-a Person.

Student s = new Student();

This declares and creates an object of the same class Student.

Student s = new Person();

This is not allowed because a Person is not always a Student.

9.5.2. Superclass Method Parameters

Another advantage of an inheritance hierarchy is that we can write methods with parameters of the superclass type and pass in subclass objects to them. For example, the print(Shape) method below could be called with many different Shape subclasses and work for Rectangles, Squares, etc.

// This will work with all Shape subclasses (Squares, Rectangles, etc.) too
public void print ( Shape s )
{
   ...
}

Coding Exercise

Notice that in the following code, the print method has a parameter of type Person, but it can be called with Student or Person objects in the main method. Which toString() method is called? It depends on whether a Person or Student is passed in at runtime. What would happen if you commented out the Student toString() method? Which one would be called now?

9.5.3. Superclass Arrays and ArrayLists

Using inheritance hierarchies, we can create arrays and ArrayLists using the superclass type and put in values that are of the subclass type. This can be very useful! For example, here is a Shape array and a Shape ArrayList that can hold any objects of the Shape subclasses.

// This shape array can hold the subclass objects too
Shape [] shapeArray = { new Rectangle (), new Square (), new Shape () };
// The shape ArrayList can add subclass objects too
ArrayList < Shape > shapeList = new ArrayList < Shape > ();
shapeList . add ( new Shape ());
shapeList . add ( new Rectangle ());
shapeList . add ( new Square ());

Notice that the add method in ArrayLists actually has a parameter type of Object, add(Object), but we can use it with any subclass object!

Coding Exercise

The code below has an ArrayList of Pets that can hold Pet or Dog objects. Notice that the loop works with a variable of type Pet because Dogs are Pets too!

Check your understanding

9-5-6: Which of the following reasons for using an inheritance hierarchy are valid?

1. Object methods from a superclass can be used in a subclass without rewriting or copying code.

2. Objects from subclasses can be passed as arguments to a method that takes an argument of the parent type.

3. Objects from subclasses can be stored in the same array of the parent type.

4. All of the above

5. None of the above

V

In fact, all of the reasons listed are valid. Subclasses can reuse object methods written for superclasses without code replication, subclasses can be stored in the same array when the array is declared to be of the parent type, and objects of subclasses can passed as arguments of the superclass type. All of which make writing code more streamlined.

IV

All of these are valid reasons to use an inheritance hierarchy.

I and II

III is also valid. In some cases you might want to store objects of subclasses together in a single array declared to be of the parent type, and inheritance allows for this.

I and III

II is also valid. In some cases a single method is applicable for a number of subclasses, and inheritance allows you to pass objects of the subclasses to the same method if it takes an argument of the parent type, instead of writing individual methods for each subclass.

I only

I and III are also valid, in some cases a single method is applicable for a number of subclasses, and inheritance allows you to pass all the subclasses to the same method instead of writing individual methods for each subclass and you might want to store subclasses together in a single array, and inheritance allows for this.

9.5.4. Programming Challenge : Shopping Cart

The following code contains a class called ShoppingCart that simulates a grocery store or an online store's shopping cart. It has an ArrayList called order that you can use to add Items to the shopping cart. The Item class keeps track of the name and the price of each Item. If you run the code below, you will see that it adds 2 items to the cart and then prints out the total order. It may be easier to follow and change the code in this repl.it link. We encourage you to work in pairs.

In this challenge, you will add a new class called DiscountedItem that extends the Item class. The ArrayList of Items will still work since it can hold the subclasses of Items too! The ShoppingCart printOrder() method will work with Items and DiscountedItems but note that it has an if statement that treats DiscountedItems differently.

In the DiscountedItem subclass,

1. Add an instance variable for the discount amount.

2. Add constructors that call the super constructor Item.

3. Add get/set methods for discount. The get method is given below but you should modify it.

4. Add a toString() method that returns a string that includes a call to the super toString() method that will print out the price as well as the discount amount using the super.valueToString() method to format it. You could put the discount in parentheses with a minus sign in front of it like "(- $.50)".

5. Uncomment the code in the main method to test adding DiscountedItems to the cart.

6. If you used repl.it or another IDE to complete this challenge, copy the code for DiscountedItem into the ActiveCode below so that it is saved for the next lesson.

9.5.5. Summary

An inheritance hierarchy of subclasses inheriting from superclasses can be formed with Object being the top of the hierarchy.

When a class S "is-a" class T, T is referred to as a superclass, and S is referred to as a subclass.

If S is a subclass of T, then a reference of type T can be used to refer to an object of type T or S. This is called polymorphism, defined more in the next lesson.

Declaring references of type T, when S is a subclass of T, is useful in the declaring formal method parameters of type T, arrays of type T[], and ArrayList<T> of type T so that all the subclasses of T can also be used with these.

You have attempted of activities on this page

# data[].attributes.attachment_link.title
9.5. Inheritance Hierarchies - AP CSAwesome

# data[].attributes.attachment_link.description
If you have multiple subclasses that inherit from a superclass, you can form an inheritance hierarchy. Every subclass is-a or is a kind of the superclass. For example, here is an inheritance hierarchy of Shapes. Square is-a Rectangle and a subclass of Rectangle. Rectangle is-a Shape and a subclass of Shape.

# data[].attributes.body
public class ClimbInfo
{
String name;
int time;
/** Creates a ClimbInfo object with name peakName and time climbTime.
* @param peakName the name of the mountain peak
* @param climbTime the number of minutes taken to complete the climb
*/
public ClimbInfo(String peakName, int climbTime)
{
name = peakName;
time = climbTime;
}
/** @return the name of the mountain peak
*/
public String getName()
{
return name;
}
/** @return the number of minutes taken to complete the climb
*/
public int getTime()
{
return time;
}
// There may be instance variables, constructors, and methods that are not shown.
}

# data[].attributes.body
import java.util.ArrayList;

public class ClimbingClub
{
/** The list of climbs completed by members of the club.
* Guaranteed not to be null. Contains only non-null references.
*/
public ArrayList<ClimbInfo> climbList;

/** Creates a new ClimbingClub object. */
public ClimbingClub()
{ climbList = new ArrayList<ClimbInfo>(); }

/** Adds a new climb with name peakName and time climbTime to the list of climbs.
* @param peakName the name of the mountain peak climbed
* @param climbTime the number of minutes taken to complete the climb
*/
public void addClimbA(String peakName, int climbTime) {

}
public void addClimbB(String peakName, int climbTime) {

}

/** @return the number of distinct names in the list of climbs */
public int distinctPeakNames() {

return 0;
}

// There may be instance variables, constructors, and methods that are not shown.
public String toString() {
String ret = "";
for (int i = 0; i < climbList.size(); i++) {
ret += climbList.get(i).getName()+", "+climbList.get(i).getTime()+"\n";
}
return ret;
}

}

# data[].attributes.body
public class ClimbMain {

public static void main(String[] args) {
ClimbingClub hikerClub = new ClimbingClub();
hikerClub.addClimbA("Monadnock", 274);
hikerClub.addClimbA("Whiteface", 301);
hikerClub.addClimbA("Algonquin", 225);
hikerClub.addClimbA("Monadnock", 344);
System.out.println("FIFO");
System.out.println(hikerClub);
//System.out.println("Distinct Peak Names: "+hikerClub.distinctPeakNames());

ClimbingClub sortedClub = new ClimbingClub();

sortedClub.addClimbB("Z", 344);
sortedClub.addClimbB("Monadnock", 274);
sortedClub.addClimbB("Whiteface", 301);
sortedClub.addClimbB("Algonquin", 225);
sortedClub.addClimbB("Monadnock", 344);

sortedClub.addClimbB("S", 344);
sortedClub.addClimbB("X", 344);
sortedClub.addClimbB("Y", 344);
System.out.println("Sorted");
System.out.println(sortedClub);
//System.out.println("Distinct Peak Names: "+sortedClub.distinctPeakNames());
}

}

# data[].attributes.body
public class Student {
private String name;
private int absenceCount;

public Student(String n, int a) {
name = n;
absenceCount = a;
}

public String getName() {
return name;
}

public int getAbsenceCount() {
return absenceCount;
}

public String toString() {
return name+":"+absenceCount;
}
}

# data[].attributes.body
import java.util.*;

public class SeatingChart {

private Student[][] seats;

public SeatingChart(List<Student> studentList, int rows, int cols) {
//a번

}

public int removeAbsentStudents(int allowedAbsences) {
//b번
}

public String toString() {
String res = "";
for (int i=0; i<seats.length; i++) {
for (int j=0; j<seats[0].length-1; j++)
res = res + seats[i][j] + "  |  ";
res = res + seats[i][seats[0].length-1] + "\n";
}
return res;
}

public static void main(String[] args) {
ArrayList<Student> list = new ArrayList<Student>();
list.add(new Student("Karen", 3));
list.add(new Student("Liz", 1));
list.add(new Student("Paul", 4));
list.add(new Student("Lester", 1));
list.add(new Student("Henry", 5));
list.add(new Student("Renee", 9));
list.add(new Student("Glen", 2));
list.add(new Student("Fran", 6));
list.add(new Student("David", 1));
list.add(new Student("Danny", 3));
SeatingChart introCS = new SeatingChart(list,3,4);
System.out.println(introCS);
introCS.removeAbsentStudents(4);
System.out.println(introCS.removeAbsentStudents(4));
System.out.println();
System.out.println(introCS);
}
}

# data[].attributes.attachment_link.readable_text
Time estimate: 45 min.

In this lesson, you will learn how to use nested loops to traverse a 2D Array.

Arrays know their length (how many elements they can store). The length is a public read-only field so you can use dot-notation to access the field ( arrayName.length ). The length of the outer array is the number of rows and the length of one of the inner arrays is the number of columns.

ticketInfo . length // returns the number of rows
ticketInfo [ 0 ] . length // returns the number of columns

Note

Note that length is a field and not a method, so you don't add parentheses after length. However, if you use parentheses after length during the exam, you won't lose any points. Since for the AP CSA exam all two-dimensional arrays are rectangular arrays (arrays that have the same number of columns in each row) you can just use the length of the first inner array as the number of columns as shown by ticketInfo[0].length .

Check your understanding

8-2-1: How many rows does a have if it is created as follows int[][] a = { {2, 4, 6, 8}, {1, 2, 3, 4}}; ?

2

The size of outer list is the number of rows.

4

The size of the inner list is the number of columns.

8

This is the total number of items in the array.

8-2-2: Which of the following would I use to get the value in the third row and second column from a 2D array called nums ?

nums[3][2]

This would be true if array indices started with 1 but they start with 0.

nums[2][3]

This would be true if array indicies started with 1 and the column was specified first. However, array indices start at 0 and the row is given first in row-major order.

nums[2][1]

Array indices start with 0 so the third row has an index of 2 and the second column has an index of 1.

nums[1][2]

This would be true if the column index was first, but in row-major order the row index is first.

Since you can find out the number of rows and columns in a 2D array you can use a nested for loop (one loop inside of another loop) to loop/traverse through all of the elements of a 2D array.

int [][] array = { { 1 , 2 , 3 },{ 4 , 5 , 6 }};
for ( int row = 0 ; row < array . length ; row ++ )
{
for ( int col = 0 ; col < array [ 0 ] . length ; col ++ )
{
System . out . println ( array [ row ][ col ] );
}
}

Coding Exercise

Some key things to notice about this code are:

total is declared to be a double so that the result will be a double. If total was declared to be an int then the result would be an integer and the values after the decimal point would be thrown away.

The array is passed in as an argument to the method.

The number of rows is a.length

The number of columns is a[0].length

The number of times this loop executes is the number of rows times the number of columns.

Mixed up programs

        public static int getLargest(int[][] arr)
{
---
 int largest = arr[0][0];
 int current = 0;
 for (int r = 0; r < arr.length; r++)
 {
 ---
   for (int c = 0; c < arr[0].length; c++)
   {
 ---
     current = arr[r][c];
     if (current > largest)
     {
 ---
       largest = current;
 ---
     } // end if
 ---
   } // end column loop
 ---
 } // end row loop
 return largest;
---
} // end method

You can step through this code using the Java Visualizer by clicking on the following Java Visualizer.

Most nested loops with 2D Arrays use "row-major order" where the outer loop goes through each row. However, you can write nested loops that traverse in "column-major order" like below.

Coding Exercise

8-2-6: Consider the following code segment. What is the last row of numbers printed when this code segment is executed?

int [][] points = { { 11 , 12 , 13 , 14 , 15 },
{ 21 , 22 , 23 , 24 , 25 },
{ 31 , 32 , 33 , 34 , 35 },
{ 41 , 42 , 43 , 44 , 45 }};
for ( int row = 0 ; row < points . length ; row ++ )
{
for ( int col = points [ 0 ] . length - 1 ; col >= row ; col -- )
{
System . out . print ( points [ row ][ col ] + " " );
}
System . out . println ();
}

45 44 43 42 41

Trace through the code. Notice that the inner loop stops at index row.

45

Trace through the code. Notice that the inner loop stops at index row.

41 42

Trace through the code. Notice that the inner loop works through the row backwards.

45 44

Correct!

44 45

Trace through the code. Notice that the inner loop works through the row backwards.

This lesson is continued on the next page.

You have attempted of activities on this page

# data[].attributes.attachment_link.title
8.2.1. Nested Loops for 2D Arrays (Day 1) - AP CSAwesome

# data[].attributes.attachment_link.description
Time estimate: 45 min. In this lesson, you will learn how to use nested loops to traverse a 2D Array. Arrays know their length (how many elements they can store). The length is a public read-only field so you can use dot-notation to access the field ( arrayName.length ).

# data[].attributes.body
public class ArrayPractice
{
public static void main(String[] args)
{
int[][] array = {{3, 5, 7, 8, 0}, {500, 250, 125, 784, 267, 674, 0}, {9, 8, 0}};

// Call the updateValue method three times on this array:

updateValue(array, 0, array[0].length - 2, array[0][0])

print(array);
}

//Create a method to add the correct value to the array at the correct col, row
public static void updateValue(int[][] arr, int row, int col, int value)
{

}

//Do not make alterations to this method!
public static void print(int[][] array)
{
for(int[] row: array)
{
for(int num: row)
{
System.out.print(num + " ");
}
System.out.println();
}
}
}

# data[].attributes.body
한글이 깨져서 안보이는건 아래에 사진으로 뒀음

# data[].attributes.attachment_link.readable_text
package wj;

public class ArrayToArrayListTester {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Animal cat = new Animal("cat", 4, 10);
		Animal dog = new Animal("dog", 4, 2);
		Animal spider = new Animal("Spider", 8, 3);
		Animal human = new Animal("human", 2, 30);
		Animal bear = new Animal("bear", 4, 13);
		
		Animal[] animal = {cat, dog, spider, human, bear};
		
		ArrayToArrayList test = new ArrayToArrayList(animal);
		
		System.out.println(test);
		
		test.Remove4Legs();
		
		System.out.println(test);
	
	}

}

# data[].attributes.attachment_link.readable_text
package wj;

public class Animal {
	
	String species;
	int numOflegs; 
	int age; 
	
	public Animal(String a, int b, int c) {
		species = a; 
		numOflegs = b; 
		age = c; 
	}
	
	public String getSpecies() {
		return species;
	}
	
	public int getNumOflegs() {
		return numOflegs;
	}
	
	public int getAge() {
		return age; 
	}
}

# data[].attributes.attachment_link.readable_text
The following are the methods that you need to know for the AP CS A exam. These are included on the AP CS A Java Quick Reference Sheet that you will receive during the exam so you do not need to memorize them. The E in the method headers below stands for the type of the element in the ArrayList; this type E can be any Object type. We will look at how these methods work below.

int size() returns the number of elements in the list

boolean add(E obj) appends obj to the end of the list and returns true

E remove(int index) removes the item at the index and shifts remaining items to the left (to a lower index)

void add(int index, E obj) moves any current objects at index or beyond to the right (to a higher index) and inserts obj at the index

E get(int index) returns the item in the list at the index

E set(int index, E obj) replaces the item at index with obj

As we saw in the last lesson, you can get the number of items in a ArrayList using its method. The ArrayList starts out empty with a size of 0.

Note

With arrays, you use the field to get the number of items in the array. But, with an you use the method to get the number of items in the ArrayList. You will not be penalized if you mix up length and size() in the CS A exam. The number of items in an empty ArrayList is 0.

7.2.2. Add(obj) to an ArrayList

You can add values to an ArrayList by using the method which will add the object to the end of the list, just like you would join the end of the line to board a bus.

When adding Integer objects to the list, you can use the Integer constructor like in Java version 7 which is used on the exam (although this is deprecated and no longer used in Java version 9) or you can just add the int value directly like in any Java version and it will be changed into an object automatically. This is called autoboxing. When you pull an value out of a list of that is called unboxing.

You can put any kind of Objects into an ArrayList. Even objects for a class that you wrote. For example, here is an ArrayList of Students.

7.2.3. Add(index,obj) in an ArrayList

There are actually two different methods in the class. The method adds the passed object to the end of the list. The add(index,obj) method adds the passed object at the passed index, but first moves over any existing values to higher indicies to make room for the new object.

Note

ArrayLists like arrays start numbering their elements from 0.

You can step through the code above by clicking on this Java Visualizer.

You can step through the code above by clicking on the following Java Visualizer.

7.2.4. Remove(index) from ArrayList

You can also remove values from an ArrayList by using remove(index) to remove the item at the given index from the list. This will move all the other items over in the underlying array and decrease the size of the ArrayList by 1.

Note

The method will remove the object at the index and shift left any values to the right of the current index. It doesn't remove the object that matches the integer value given. In the example above it doesn't remove the value 1. It removes the value 2 at index 1.

You can step through the code above by clicking on the following RemoveExample.

7.2.5. ArrayList get/set Methods

You can get the object at an index using and set the object at an index using listName.set(index,obj) . Set/Get are used after you add and remove elements to an ArrayList to change or retrieve them.

Notice that ArrayLists use set/get methods instead of using the square brackets array[index] that arrays use. This is because ArrayList is a class with methods that provide access to the underlying array.

You can step through the code above by clicking on the following Example1.

You can step through the code above by clicking on the following Example2.

7.2.6. Comparing arrays and ArrayLists

When do you use arrays and when do you use ArrayLists? Use an array when you want to store several items of the same type and you know how many items will be in the array and the items in the array won't change in order or number. Use an ArrayList when you want to store several items of the same type and you don't know how many items you will need in the list or when you want to remove items from the list or add items to the list while the program is running.

Here is a comparison of how to create arrays and ArrayLists:

Here is a comparison of how to access and change elements in arrays and ArrayLists.

Note that the ArrayList methods add and remove do not have a simple equivalent in arrays because they actually change the size of the underlying array and move elements over.

7.2.7. Programming Challenge : Array to ArrayList

# data[].attributes.attachment_link.description
The following are the methods that you need to know for the AP CS A exam. These are included on the AP CS A Java Quick Reference Sheet that you will receive during the exam so you do not need to memorize them.

# data[].attributes.attachment_link.readable_text
Time estimate: 90 min.

To keep track of 10 exam scores, we could declare 10 separate variables: int score1, score2, score3, ... , score10; But what if we had 100 exam scores? That would be a lot of variables! Most programming languages have a simple data structure for a collection of related data that makes this easier. In many block-based programming languages like App Inventor and Scratch, this is called a list. In Java and many programming languages, this is called an array.

An array is a block of memory that stores a collection of data items ( elements) of the same type under one name. Arrays are useful whenever you have many elements of data of the same type that you want to keep track of, but you don't need to name each one. Instead you use the array name and a number (called an index) for the position of an item in the array. You can make arrays of ints, doubles, Strings, and even classes that you have written like Students.

Here's a fun video that introduces the concept of an array and gives an example.

An array is like a row of small lockers, except that you can't cram lots of stuff into it. You can only store one value at each locker.

¶

You can store a value in an array using an index (location in the array). An array index is like a locker number. It helps you find a particular place to store your stuff and retrieve stuff. You can get or store a value from or to an array using an index.

Arrays and lists in most programming languages start counting elements from the number 0, so the first element in an array is at index 0. This is similar to how Strings are indexed in Java - the first character is at index 0. If you used App Inventor in the past, you might remember that list elements there start at 1 instead of 0, so make sure you remember that in Java, arrays start the index at 0!

¶

6-1-2: Can you think of another example of something that is like an array (like a row of lockers)?

6.1.1. Declaring and Creating an Array

When we declare a variable, we specify its type and then the variable name. To make a variable into an array, we put square brackets after the data type. For example, int[] scores means we have an array called scores that contains int values.

The declarations do not create the array. Arrays are objects in Java, so any variable that declares an array holds a reference to an object. If the array hasn't been created yet and you try to print the value of the variable, it will print null (meaning it doesn't reference any object yet).

There are two ways to create an array. You can use the keyword new to get new memory or use an initializer list to set up the values in the array.

Watch the following video which shows the two ways of creating an array with a physical model of Java memory.

6.1.2. Using new to Create Arrays

To create an empty array after declaring the variable, use the new keyword with the type and the size of the array (the number of elements it can hold). This will actually create the array in memory. You can do the declaration and the creation all in one step, see the String array names below. The size of an array is set at the time of creation and cannot be changed after that.

Note

Array elements are initialized to default values like the following.

0 for elements of type int

0.0 for elements of type double

false for elements of type boolean

null for elements of type String

¶

6.1.3. Initializer Lists to Create Arrays

Another way to create an array is to use an initializer list. You can initialize (set) the values in the array to a list of values in curly braces ({} ) when you create it, like below. In this case you don't specify the size of the array, it will be determined from the number of values that you specify.

When you create an array of a primitive type (like int ) with initial values specified, space is allocated for the specified number of items of that type and the values in the array are set to the specified values. When you create an array of an object type (like String ) with initial values, space is set aside for that number of object references. The objects are created and the object references set so that the objects can be found.

¶

Watch the following video which shows an array of String objects with a physical model of Java memory.

6.1.4. Array length

Arrays know their length (how many elements they can store). It is a public read-only instance variable so you can use dot-notation to access the instance variable ( arrayName.length ). Dot-notation is using variable name followed by a . and then the instance variable (property) name or a method name. Try the following.

Note

Note that length is an instance variable and not a method, unlike the String length() method, so you don't add parentheses after length. However, if you use parentheses after length during the exam, you won't lose any points. The length instance variable is declared as a public final int . public means you can access it and final means the value can't change.

6.1.5. Access and Modify Array Values

To access the items in an array, we use an indexed array variable which is the array name and the index inside of square bracket [ ]. Remember that an index is a number that indicates the position of an item in a list, starting at 0. Here's a comparison of App Inventor, AP CSP Pseudocode, and Java array access.

¶

An indexed variable like arrayname[index] can be used anywhere a regular variable can be used, for example to assign a new value or to get a value from the array like below.

Note

The first value in an array is stored at index 0 and the index of the last value is the length of the array minus one (since the first index is 0). Use arrayname[index] to access or modify array items.

Watch the following video which shows a physical model of Java memory setting array values.

String[] cars = {"Honda", "Volvo", "BMW"};

String v = ;

String[] cars = {"Honda", "Volvo", "BMW"};

= "Toyota";

If you want to keep track of the top 5 highest scores in a game and the names of the people with those scores, you could use two parallel arrays. One array could keep track of the scores and the other the names. You have to make sure you keep them in the same order so that the same index can be used to get correponding names and scores.

What happens if you try to access an element that is not there? Try to access a highScore or name at index 7 above to see what happens. The index must be between 0 and the length of the array - 1 or it will give an error message called ArrayIndexOutOfBoundsException .

Note

Using an index value outside of 0 - (length-1) will result in an ArrayIndexOutOfBoundsException being thrown.

One powerful feature in the array data abstraction is that we can use variables for the index! As long as the variable holds an integer, we can use it as an index.

Here's a fun String array of image filenames. The following code displays an online image using an HTML tag. (Note that this just works in this Active Code window which interprets HTML. In other Java IDEs you would need to use Java Swing graphics instead). Run the code and see that it displays images[0] which is "cow.jpg". The images array holds 5 images.

6.1.6. Programming Challenge : Countries Array

In this challenge, you will create a guide to different countries using arrays.

Use the Active Code window below to create 4 parallel arrays and initialize them using initialization lists that represent the data below. Remember that the order of these arrays has to match so that you can use the same index and get corresponding values out.

Countries: China, Egypt, France, Germany, India, Japan, Kenya, Mexico, United Kingdom, United States

Capitals: Beijing, Cairo, Paris, Berlin, New Delhi, Tokyo, Nairobi, Mexico City, London, Washington D.C.

Languages: Chinese, Arabic, French, German, Hindi, Japanese, Swahili, Spanish, English, English

Filenames for map images: China.jpg, Egypt.jpg, France.jpg, Germany.jpg, India.jpg, Japan.jpg, Kenya.jpg, Mexico.jpg, UK.jpg, US.jpg

1. You are encouraged to add additional country, capital, and language names that match in position in the parallel arrays to represent your family origins or places you would like to visit. Although we do not have image files for each country in the CSAwesome map images, we do have regional map images called south-america.png, central-america.png, north-america.png, asia-pacific.png, europe.png, africa.png, and middle-east.png which you can use. Note that these are png files and not jpg. If you create more maps for your project, you can have your teacher share it in the teaching-csawesome google group to contribute to this map image collection.

2. Choose a random number using Math.random() and the length of one of the arrays and save it in a variable called index.

3. Print out the country name, its capital, and its language, and the map image for that country using the random index to access the corresponding item in each parallel array. For the images, the printHTMLimage method has been given to get the image URL online and print it out as an HTML image.

4. Optional Extra Challenge: If you have more time for this project, you can combine what you learned in the last unit to refactor your code (which means restructure without changing the functionality) to make it object-oriented. Create a Country class that stores the country name, capital, language, and image file. In the main method, create an array of 10 Country objects with the data for each country passed to its constructor, and use a random number to choose a country object from the array and display its attributes. See the array of turtles in the next section below for help on how to create an array of objects.

6.1.7. Design an Array of Objects for your Community

So far, we have seen arrays of ints and Strings, but we can create an array of any type. For example, the following program creates an array of Turtle objects. Notice that for an array of objects, we must call the constructor of each object to initialize the array elements, for example array[index] = new ClassName(); . And we can use array[index].method() to call a method of an object in the array.

In Unit 5, you came up with a class of your own choice relevant to you or your community. In this unit, you will create an array to hold objects of your class.

1. Copy your class from lesson 5.6 below.

2. In the main method, create an array of 3 objects of your class.

3. Initialize array elements indexed 0 to 2 to new objects of your class using its constructor.

4. Call the print method of each object in the array using the array index.

6.1.8. Summary

Arrays represent collections of related data all of the same data type.

The size of an array is established at the time of creation and cannot be changed.

Arrays can store either primitive data or object reference data.

When an array is created using the keyword new, all of its elements are initialized with a specific value based on the type of elements:

Elements of type int are initialized to 0

Elements of type double are initialized to 0.0

Elements of type boolean are initialized to false

Elements of a reference type are initialized to the reference value null. No objects are automatically created.

Initializer lists can be used to create and initialize arrays.

Square brackets ([ ]) are used to access and modify an element in an array using an index. The indexed array variable, for example array[index], can be used anywhere a regular variable can be used, for example to get or assign values.

The valid index values for an array are 0 through one less than the number of elements in the array, inclusive. Using an index value outside of this range will result in an ArrayIndexOutOfBoundsException being thrown.

6.1.9. AP Practice

We will see in the next lesson that the index of an array is often a variable named i that is used in loops to traverse an array. In challenging AP problems, you will see mathematical expressions inside the square brackets ([] ). For example, array[i-1] refers to the previous element right before the ith element in array, and array[i+1] refers to the next element after the ith element. In the problems below, note that arrays can be passed in as arguments to methods and returned as values, just like any variable.

6-1-17: Consider the following method. Given an array initialized to {4, 10, 15} , which of the following represents the contents of the array after a call to mystery(array, 2) ?

public void mystery ( int [] a , int i )
{
a [ i ] = a [ i - 1 ] * 2 ;
}

[8, 20, 30]

This would only be true if all elements were doubled by the method.

[4, 8, 15]

This would only be true if the call was ``mystery(array, 1)``. Remember that array indexing starts at 0.

[8, 10, 15]

This would only be true if the method body had ``a[i-1] = a[i-1] * 2;``

[4, 10, 20]

Correct. array[2] = array[1] * 2 = 10 * 2 = 20.

[4, 8, 30]

Note that only 1 array element is changed.

6-1-18: Consider the following method. Which of the following code segments, appearing in the same class as the mystery method, will result in array2 having the contents {5, 10, 20} ?

public int [] mystery ( int [] a , int i , int value )
{
a [ i + 1 ] = a [ i ] + value ;
return a ;
}

This would result in {5, 15, 15} .

This would result in {5, 5, 20} .

Correct! a[i+1] = a[2] = a[i] + value = a[1] + 10 = 10 + 10 = 20.

This would result in an ArrayIndexOutOfBoundsException .

This would result in {5, 10, 30} .

6.1.10. Arrays Game

Try the game below to practice arrays. Click on Arrays and click on the element of the * array that would be printed out by the given code. If you're stuck, check on Labels to see the indices. We encourage you to work in pairs and see how high a score you can get.

You have attempted of activities on this page

# data[].attributes.attachment_link.title
6.1. Array Creation and Access - AP CSAwesome

# data[].attributes.attachment_link.description
Time estimate: 90 min. To keep track of 10 exam scores, we could declare 10 separate variables: int score1, score2, score3, ... , score10; But what if we had 100 exam scores? That would be a lot of variables! Most programming languages have a simple data structure for a collection of related data that makes this easier.

# data[].attributes.body
import java.util.ArrayList;

public class ArrayToArrayList {
private ArrayList<Animal> AtA ;

public ArrayToArrayList(Animal[]a) {
//위에 있는 AtA 채워주세요
}

public void Remove4Legs() {
//다리가 4개인 녀석만 지워주는 메소드 적어주세요
}

public String toString() {
String result = "";
for(int i = 0; i<AtA.size(); i++) {
System.out.println(AtA.get(i).getSpecies()
+ " has " + AtA.get(i).getNumOflegs()
+ " age: " + AtA.get(i).getAge());
}
return result;
}
}

# data[].attributes.body
Review review1 = new Review(4, "Good! Thx");
Review review2 = new Review(3, "OK site");
Review review3 = new Review(5, "Great!");
Review review4 = new Review(2, "Poor! Bad");
Review review5 = new Review(3, "");
Review[] reviews = {review1, review2, review3, review4, review5};

ReviewAnalysis RA = new ReviewAnalysis(reviews);

System.out.println( RA.getAverageRating() );
System.out.println( RA.collectComments() );

# data[].attributes.body
public class Review {
private int rating;
private String comment;

public Review(int r, String c) {
rating = r;
comment = c;
}

public int getRating() {
return rating;
}

public String getComment() {
return comment;
}
}

# data[].attributes.body
public String toString()
{
String s = "";
for( int[] r : grid )
{
for( int v : r )
s = s + v + " ";
s += "\n";
}
return s;
}

public static void main(String[] args)
{
Data data = new Data();
System.out.println( data );
data.repopulate();
System.out.println( data );
System.out.println(data.countIncreasingCols());
}

# data[].attributes.body
CodingBat Java String-2 catDog

# data[].attributes.body
import java.util.Arrays;

public class DiverseArray {

public static void main(String[] args) {

int[] arr1 = { 1, 3, 2, 7, 3 };
System.out.println(Arrays.toString(arr1)+": ArraySum = "+arraySum(arr1));

int[][] arr2 = {
{1, 3, 2, 7, 3},
{10,10,4,6,2},
{5,3,5,9,6},
{7,6,4,2,1}
};

for ( int[] tt : arr2) {
System.out.println(Arrays.toString(tt));
}
System.out.println(": RowSum = "+Arrays.toString( rowSums(arr2) ) );

int[][] arr3 = {
{1, 1, 5, 3, 4},
{12, 7, 6, 1, 9},
{8, 11, 10, 2, 5},
{3, 2, 3, 0, 6}
};

if (isDiverse(arr2)) {
System.out.println("arr2 is diverse");
} else {
System.out.println("arr2 is NOT diverse");
}

if (isDiverse(arr3)) {
System.out.println("arr3 is diverse");
} else {
System.out.println("arr3 is NOT diverse");
}
/*
if (isDiverse(arr2)) System.out.println("arr2 is diverse");
else System.out.println("arr2 is NOT diverse");
if (isDiverse(arr3)) System.out.println("arr3 is diverse");
else System.out.println("arr3 is NOT diverse");
*/

}

// complete the following code!!
public static int arraySum(int[] arr){

}

// complete the following code!!
public static int[] rowSums(int[][] arr){

}

// complete the following code!!
public static boolean isDiverse(int[][] arr2D){

}

}

# data[].attributes.attachment_link.readable_text
The following are the methods that you need to know for the AP CS A exam. These are included on the AP CS A Java Quick Reference Sheet that you will receive during the exam so you do not need to memorize them. The E in the method headers below stands for the type of the element in the ArrayList; this type E can be any Object type. We will look at how these methods work below.

int size() returns the number of elements in the list

boolean add(E obj) appends obj to the end of the list and returns true

E remove(int index) removes the item at the index and shifts remaining items to the left (to a lower index)

void add(int index, E obj) moves any current objects at index or beyond to the right (to a higher index) and inserts obj at the index

E get(int index) returns the item in the list at the index

E set(int index, E obj) replaces the item at index with obj

As we saw in the last lesson, you can get the number of items in a ArrayList using its method. The ArrayList starts out empty with a size of 0.

Note

With arrays, you use the field to get the number of items in the array. But, with an you use the method to get the number of items in the ArrayList. You will not be penalized if you mix up length and size() in the CS A exam. The number of items in an empty ArrayList is 0.

7.2.2. Add(obj) to an ArrayList

You can add values to an ArrayList by using the method which will add the object to the end of the list, just like you would join the end of the line to board a bus.

When adding Integer objects to the list, you can use the Integer constructor like in Java version 7 which is used on the exam (although this is deprecated and no longer used in Java version 9) or you can just add the int value directly like in any Java version and it will be changed into an object automatically. This is called autoboxing. When you pull an value out of a list of that is called unboxing.

You can put any kind of Objects into an ArrayList. Even objects for a class that you wrote. For example, here is an ArrayList of Students.

7.2.3. Add(index,obj) in an ArrayList

There are actually two different methods in the class. The method adds the passed object to the end of the list. The add(index,obj) method adds the passed object at the passed index, but first moves over any existing values to higher indicies to make room for the new object.

Note

ArrayLists like arrays start numbering their elements from 0.

You can step through the code above by clicking on this Java Visualizer.

You can step through the code above by clicking on the following Java Visualizer.

7.2.4. Remove(index) from ArrayList

You can also remove values from an ArrayList by using remove(index) to remove the item at the given index from the list. This will move all the other items over in the underlying array and decrease the size of the ArrayList by 1.

Note

The method will remove the object at the index and shift left any values to the right of the current index. It doesn't remove the object that matches the integer value given. In the example above it doesn't remove the value 1. It removes the value 2 at index 1.

You can step through the code above by clicking on the following RemoveExample.

7.2.5. ArrayList get/set Methods

You can get the object at an index using and set the object at an index using listName.set(index,obj) . Set/Get are used after you add and remove elements to an ArrayList to change or retrieve them.

Notice that ArrayLists use set/get methods instead of using the square brackets array[index] that arrays use. This is because ArrayList is a class with methods that provide access to the underlying array.

You can step through the code above by clicking on the following Example1.

You can step through the code above by clicking on the following Example2.

7.2.6. Comparing arrays and ArrayLists

When do you use arrays and when do you use ArrayLists? Use an array when you want to store several items of the same type and you know how many items will be in the array and the items in the array won't change in order or number. Use an ArrayList when you want to store several items of the same type and you don't know how many items you will need in the list or when you want to remove items from the list or add items to the list while the program is running.

Here is a comparison of how to create arrays and ArrayLists:

Here is a comparison of how to access and change elements in arrays and ArrayLists.

Note that the ArrayList methods add and remove do not have a simple equivalent in arrays because they actually change the size of the underlying array and move elements over.

7.2.7. Programming Challenge : Array to ArrayList

# data[].attributes.attachment_link.description
The following are the methods that you need to know for the AP CS A exam. These are included on the AP CS A Java Quick Reference Sheet that you will receive during the exam so you do not need to memorize them.

# data[].attributes.body
public String toString() {
String result = "Array is "+numRows+" x "+numCols+"\n";
for (int i=0; i<entries.size(); i++)
result += entries.get(i) + "\n";
return result;
}

# data[].attributes.body
public String toString() {
return "A["+row+"]["+col+"] = "+value;
}

# data[].attributes.body
public static void main(String[] args) {

// // (a)
String[] wordArray = {"wheels", "on", "the", "bus"};
RandomStringChooser sChooser = new RandomStringChooser(wordArray);
System.out.println();
for(int k=0; k<6; k++) {
System.out.print(sChooser.getNext()+" ");
}
System.out.println();

//(b)
RandomLetterChooser letterChooser = new RandomLetterChooser("cat");
for(int k=0; k<4; k++) {
System.out.print(letterChooser.getNext()+"");
}
System.out.println();

}

# data[].attributes.body
public static String[] getSingleLetters(String str) {
String[] result = new String[str.length()];
for (int i=0; i<str.length(); i++)
result[i] = str.substring(i, i+1);
return result;
}

# data[].attributes.body
AP Computer Science A 2016 Free-Response Questions (collegeboard.org)

# data[].attributes.body
@Override
public String toString() {
String str = "";
str = machineId + ":" + description;
return str;
}