# 14--ArrayList related exercises

Keywords: Attribute

## First question

• Enter the student information on the keyboard and save it in the set.

``` Cycle entry method: 1: continuous entry, 0: end entry.
Define student class, attribute is name, age, use student object to save input data.
Use the ArrayList set to save the student object. After entering, traverse the set.
```
• Code implementation, the effect is as shown in the figure:

```public class Test1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Student> list = new ArrayList<>();
while (true) {
System.out.println("1.Input information 0.sign out");
int i = scanner.nextInt();
switch (i) {
case 1:
inputStu(list , scanner);
break;
case 0:
System.out.println("Input completed");
}
if (i == 0){
break;
}
}

for (int i = 0; i < list.size(); i++) {
Student student = list.get(i);
student.show();
}
}

private static void inputStu(ArrayList<Student> list , Scanner sc) {
String name = sc.next();
int age = sc.nextInt();
Student student = new Student(name, age);
}
}

class Student{
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void show() {
System.out.println( "Student name=" + name + ", Age=" + age);
}
}
```

## Second question

• Collection tool class.

``` Define the findIndex method, find an element in a collection, and return the first index.
Define the replace method to replace all elements in a collection with new ones.
```
• Code implementation, the effect is as shown in the figure:

```public class Test2 {
public static int findIndex(List<Integer> list, int i){
int index = -1;
for (int j = 0; j < list.size(); j++) {
if (list.get(j) == i) {
index = j;
break;
}
}
return index;
}
public static void replace(List<Integer> list,Integer oldValue,Integer newValue){
for (int i = 0; i < list.size(); i++) {
if (list.get(i) == oldValue) {
list.set(i, newValue);
}
}
}
}
```

## The third question

• Simulate the distribution of class test scores, and count the number of students in 100-80, 79-60, 59-40, 39-0 stages respectively.

``` Define the getScoreList method, randomly generate 50 numbers from 0 to 100.
Define the countScore method and count the scores of each stage.
Define the printCount method to print the statistics of each stage.
```
• Code implementation, the effect is as shown in the figure:

```public class Test3 {
public static void main(String[] args) {
// Get random scores
ArrayList<Integer> scoreList = getScoreList();
// Variables defining the count
ArrayList<Integer> countList = countScore(scoreList);
// Print statistics
printCount(countList);
}

private static void printCount(ArrayList<Integer> countList) {
int start = 100;
int end = 80;
for (int i = 0; i < countList.size(); i++) {
Integer integer = countList.get(i);
System.out.println(start + "\t branch --" + end + " \t branch:" + integer+"people");
if (i == 0){
start-=21;
end -=20;
}else if (i == countList.size()-2){
start-=20;
end-=40;
}else {
start -= 20;
end -= 20;

}
}
}
public static ArrayList<Integer> countScore(ArrayList<Integer> scoreList) {
ArrayList<Integer> countList = new ArrayList<>();
int count100 = 0;
int count79 = 0;
int count59 = 0;
int count39 = 0;

for (int i = 0; i < scoreList.size(); i++) {
Integer score = scoreList.get(i);
if (score <= 100 && score >= 80) {
count100++;
} else if (score <= 79 && score >= 60) {
count79++;
} else if (score <= 59 && score >= 40) {
count59++;
} else {
count39++;
}
}

return countList;
}

public static ArrayList<Integer> getScoreList() {
ArrayList<Integer> list = new ArrayList<>();
Random r = new Random();
for (int i = 0; i < 50; i++) {
int x = r.nextInt(100);
}
return list;
}
}

```

## Fourth question:

• Randomly generate n playing cards.

• Code implementation, the effect is as shown in the figure:

• Development tips:

``` Use the collection to save all poker objects.
From all cards, randomly remove n cards and save to a new set.
The value of n can't exceed the range of a deck of playing cards.
```

```public class Test4 {
public static void main(String[] args) {
int n = 5;
ArrayList<Card> cards = randomCard(n);

if (cards != null) {
System.out.println("random"+ n +"Cards:" );
for (int i = 0; i < cards.size(); i++) {
Card card = cards.get(i);
card.showCard();
}
}else {
System.out.println(n+"Beyond the scope,Unable to get card" );
}

System.out.println();
System.out.println();
int n2 = 55;
ArrayList<Card> cards2 = randomCard(n2);

if (cards2 != null) {
System.out.println("random"+ n2 +"Cards:" );
for (int i = 0; i < cards.size(); i++) {
Card card = cards.get(i);
card.showCard();
}
}else {
System.out.println("random"+ n2 +"Cards:\r\n Beyond the scope,Unable to get" );
}
}
public static ArrayList<Card> randomCard(int n) {
if (n > 54 || n < 0)
return null;

ArrayList<Card> rList = new ArrayList<>();
ArrayList<Card> cards = allCard();

Random r = new Random();
for (int i = 0; i < n; i++) {
int index = r.nextInt(cards.size());
Card rCard = cards.remove(index);
}
return rList;
}

public static ArrayList<Card> allCard() {
ArrayList<Card> allList = new ArrayList<>();
// Decor array
String[] hs = {"spade", "heart", "Plum blossom", "Square tablet"};
// Points array
String[] ds = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"};

for (int H = 0; H < hs.length; H++) {
for (int d = 0; d < ds.length; d++) {
Card card = new Card(hs[H], ds[d]);
}
}
return allList;
}
}

class Card {
private String ds; // point
private String hs; // Decor
public Card(String ds, String hs) {
this.ds = ds;
this.hs = hs;
}
public void showCard() {
System.out.print(ds + hs+" ");
}
}
```

## Question five

• Customize the MyList class to access the elements.

``` Define the add method to save the elements and add the tail of MyList.
Define the remove method to get the last added element and remove it from MyList.
Define the show method to display the elements in MyList.
```
• Code implementation, the effect is as shown in the figure:

```public class Test5 {
public static void main(String[] args) {
MyList myList = new MyList();
for (int i = 0; i < 3; i++) {
}
myList.show();

Integer remove = myList.remove();
System.out.println("Get element:");
System.out.println(remove);
System.out.println("After getting elements:");
myList.show();
}
}

class MyList {
ArrayList<Integer> ml = new ArrayList<>();

}
public Integer remove() {
Integer remove = ml.remove(ml.size() - 1);
return remove;
}

public void show(){
System.out.println(ml);
}
}
```

## Question six

• Customize 4 student objects, add them to the collection, and traverse
```public class Test02ArrayList {
public static void main(String[] args) {
//Create collection object
ArrayList<Student> list = new ArrayList<Student>();
//Create student object
Student s1 = new Student("Zhao Liying",18);
Student s2 = new Student("Tang Yan",20);
Student s3 = new Student("Jingtian",25);
Student s4 = new Student("Liuyan",19);
//Add student objects to the collection as elements
//Ergodic set
for(int x = 0; x < list.size(); x++) {
Student s = list.get(x);
System.out.println(s.getName()+"‐‐‐"+s.getAge());
}
}
}

```

## Question seven

• Define a method to print the collection in the specified format (ArrayList type as a parameter), expand the collection with {}, and separate each element with @. Format references {element @ element @ element}.
```public class Test03ArrayList {
public static void main(String[] args) {
// Create collection object
ArrayList<String> list = new ArrayList<String>();
// Call method
printArrayList(list);
}
public static void printArrayList(ArrayList<String> list) {
// Splice left parenthesis
System.out.print("{");
// Ergodic set
for (int i = 0; i < list.size(); i++) {
// Get element
String s = list.get(i);
// Splice @ symbol
if (i != list.size() ‐ 1) {
System.out.print(s + "@");
} else {
// Splice right parenthesis
System.out.print(s + "}");
}
}
}
}
```

## Question eight

• Define a method to get a collection of all even elements (ArrayList type as return value)
```public class Test04ArrayList {
public static void main(String[] args) {
// Create Random object
Random random = new Random();
// Create ArrayList object
ArrayList<Integer> list = new ArrayList<>();
// Add random number to set
for (int i = 0; i < 20; i++) {
int r = random.nextInt(1000) + 1;
}
// Calling even collection methods
ArrayList<Integer> arrayList = getArrayList(list);
System.out.println(arrayList);
}
public static ArrayList<Integer> getArrayList(ArrayList<Integer> list) {
// Create a small collection to hold even numbers
ArrayList<Integer> smallList = new ArrayList<>();
// Traversal list
for (int i = 0; i < list.size(); i++) {
// Get element
Integer num = list.get(i);
// Judge as even, add to small set
if (num % 2 == 0){