Java exercises

1, Basic grammar flow control

1. Define integer variables A and b, and write the program to exchange the values of a and b (temp variable cannot be used)

public class changeTest {
public static void main(String[] args) {
change();
}

public static void change() {
int a = 3;
int b = 4;

a = a + b;    // a=7
b = a - b;    // 7-3 b=4
a = a - b;    // 7-4 a=3
System.out.println(a);
System.out.println(b);
}
}

2. Define an integer variable and assign a five digit positive integer as the initial value to judge whether it is a palindrome number. For example, 12321 bits are the same as 10000 bits, and 10 bits are the same as 1000 bits.

public class huiWenTest {
public static void main(String[] args) {
//Ternary O(1)
//        test1();

//Array O(n+n) O(n)
test2();
}

public static void test1() {
int num = 45654;

int ge = num % 10;
int shi = num / 10 % 10;
int qian = num / 1000 % 10;
int wan = num / 10000 % 10;

boolean result = (ge == wan && shi == qian) ? true : false;
System.out.println(num + "Number of palindromes:" + result);
}

public static void test2() {

Scanner sc = new Scanner(System.in);
int[] num = new int;
System.out.println("Please enter a five digit number");
int n = sc.nextInt();
for (int i = num.length - 1; i >= 0; i--) {
num[i] = n % 10;
n /= 10;
}
//Reverse comparison
for (int i = 0; i < num.length / 2; i++) {
if (num[i] != num[num.length - 1 - i]) {
System.out.println("This number is not a palindrome number");
return;
}
}
System.out.println("This number is the palindrome number");
}
}

3. Define an integer variable and assign any five bit positive integer as the initial value to output the sum of the numbers of each bit

public class sumTest {
public static void main(String[] args) {
sum();
}

public static void sum() {
int number = 12345;
int ge = number % 10;
int shi = number / 10 % 10;
int bai = number / 100 % 10;
int qian = number / 1000 % 10;
int wan = number / 10000 % 10;

System.out.println("The result is:" + (wan + qian + bai + shi + ge));
}
}

4. The starting price of a taxi in a city (within 2 kilometers) is 8 yuan. If it exceeds 2 kilometers, it is calculated as 4.5 yuan per kilometer. It is required to calculate the cost according to the distance.

public class Demo01 {
public static void main(String[] args) {

double price = 8;
int kilometre;

Scanner input = new Scanner(System.in);

if (input.hasNextInt()) {
kilometre = input.nextInt();
if (kilometre > 2) {
price += (kilometre - 2) * 4.5;
System.out.println("The price is:" + price);
} else {
System.out.println("The price is:" + price);
}

} else {
System.out.println("The data you entered is incorrect");
}
}
}

5. Enter the year to judge whether the entered year is a leap year. (the condition of leap years is that they can be divided by 4, but not by 100; or they can be divided by 400.)

public class Demo02 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int year = sc.nextInt();
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
System.out.println(year + "Year is a leap year");
} else {
System.out.println(year + "Not a leap year");
}
}
}

6. It is required to input the month, judge the season of the month and output the season

public class Demo03 {
public static void main(String[] args) {

int inputMonth;

Scanner input = new Scanner(System.in);

if (input.hasNextInt()) {
inputMonth = input.nextInt();
if (inputMonth > 0 && inputMonth < 13) {
switch (inputMonth) {
case 12:
case 1:
case 2:
System.out.println(inputMonth + "Month is winter");
break;
case 3:
case 4:
case 5:
System.out.println(inputMonth + "June is spring");
break;
case 6:
case 7:
case 8:
System.out.println(inputMonth + "June is summer");
break;
case 9:
case 10:
case 11:
System.out.println(inputMonth + "September is autumn");
break;
}
} else {
System.out.println("The month you entered is out of range " + inputMonth);
}
} else {
System.out.println("The data you entered is incorrect");
}
}
}

7. According to the sales electricity price table of the State Grid, residents' domestic electricity is charged according to three gradients: 0.43 yuan per kilowatt hour for the part with monthly power consumption of 150 kWh and below, 0.45 yuan for the part with 151-400 kwh, and 0.52 yuan for the part with power consumption above 401 kWh. Please write a program to calculate the fees to be paid when inputting the user's power consumption.

public class Demo04 {
public static void main(String[] args) {
//Total cost
double finalPrice;
//Electric quantity
int electricQuantity ;

Scanner input = new Scanner(System.in);

if(input.hasNextInt()) {

electricQuantity = input.nextInt() ;

if(electricQuantity<0) {
System.out.println("Meter reversal");
}else if(electricQuantity<150) {
finalPrice = electricQuantity*0.43;
System.out.println("The price is:"+finalPrice);
}else if(electricQuantity<400) {
finalPrice = 150*0.43+(electricQuantity-150)*0.45;
System.out.println("The price is:"+finalPrice);
}else if(electricQuantity>400) {
finalPrice = 150*0.43+(400-150)*0.45+(electricQuantity-400)*0.52;
System.out.println("The price is:"+finalPrice);
}
}else {
System.out.println("The data you entered is incorrect");
}
}
}

8. The mall discounts according to the member points: 10% off for 2000 points, 8% off for 4000 points, 7.5% off for 8000 points and 7% off for more than 8000 points. The if else if structure is used to manually input the shopping amount and points and calculate the payable amount.

public class Demo05 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double shop = sc.nextDouble();
int score = sc.nextInt();
if (score < 2000) {
shop *= 0.9;
System.out.println("Current consumption" + shop + "element");
} else if (score >= 2000 && score <= 4000) {
shop *= 0.8;
System.out.println("Current consumption" + shop + "element");
} else if (score <= 8000 && score > 4000) {
shop *= 0.75;
System.out.println("Current consumption" + shop + "element");
} else if (score > 8000) {
shop *= 0.7;
System.out.println("Current consumption" + shop + "element");
} else {
System.out.println("Sorry, no discount");
}
}
}

9. There are 12 months in a year, and the days of each month are different. The 31 days of the big month are January, March, may, July, August, October and December respectively, and the 30 days of the small month are April, June, September and November respectively. In addition, February is special. February in a normal year has only 28 days, while February in a leap year has 29 days. The user inputs the year, month and day on the console, and the program calculates how many days the input date is in the current year. (for example, if you input December 31, 2000, the output should be day 366).

public class Demo06 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter year");
int year = sc.nextInt();
System.out.println("Enter month");
int mouth = sc.nextInt();
int sum = 0;

for (int i = 1; i <= mouth; i++) {
switch (i) {
//Big moon
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
sum += 31;
break;

//Xiaoyue
case 4:
case 6:
case 9:
case 11:
sum += 30;
break;

case 2:
//Runnian Pingnian
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
sum += 29;
} else
sum += 28;
break;
}
}
System.out.println(year + "year" + mouth + "month" + "The total number of days is:" + sum);
}
}

10. Output and print regular right triangle, inverted right triangle and isosceles triangle

public class Demo07 {
public static void main(String[] args) {
//        test1();
test2();
//        test3();
}

//Regular right triangle
public static void test1() {
for (int i = 0; i < 5; i++) {
for (int j = 0; j < i + 1; j++) {
System.out.print("*");
}
System.out.println();
}
}

//Inverted right triangle
public static void test2() {
//        Method 1
//        for (int i = 0; i < 5; i++) {
//            for (int j = 0; j < 5 - i ; j++) {
//                System.out.print("*");
//            }
//            System.out.println();

for (int i = 0; i < 5; i++) {
for (int j = 5; j > i; j--) {
System.out.print("*");
}
System.out.println();
}
}

//an isosceles triangle
public static void test3() {
for (int i = 1; i <= 5; i++) {
for (int j = 5; j >= i; j--)
System.out.print(" ");
for (int j = 1; j <= i; j++)
System.out.print("*");
for (int j = 1; j < i; j++)
System.out.print("*");
System.out.println();
}
}
}
*
**
***
****
*****

Process finished with exit code 0
*****
****
***
**
*

Process finished with exit code 0
*
***
*****
*******
*********

Process finished with exit code 0

11. Print 99 multiplication table

public class Demo08 {
public static void main(String[] args) {
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j +"*"+i + "=" + i*j + "\t");
}
System.out.println();
}
}
}
1*1=1
1*2=2	2*2=4
1*3=3	2*3=6	3*3=9
1*4=4	2*4=8	3*4=12	4*4=16
1*5=5	2*5=10	3*5=15	4*5=20	5*5=25
1*6=6	2*6=12	3*6=18	4*6=24	5*6=30	6*6=36
1*7=7	2*7=14	3*7=21	4*7=28	5*7=35	6*7=42	7*7=49
1*8=8	2*8=16	3*8=24	4*8=32	5*8=40	6*8=48	7*8=56	8*8=64
1*9=9	2*9=18	3*9=27	4*9=36	5*9=45	6*9=54	7*9=63	8*9=72	9*9=81

Process finished with exit code 0

12. Print all daffodils in the three digits. The so-called "daffodils" is an integer whose value is equal to the cubic sum of each digit. For example, 153 is a number of daffodils, because 153 = 1 ³+ five ³+ three ³

public class Demo09 {
public static void main(String[] args) {

int i, bai, shi, ge;
for (i = 100; i < 1000; i++) {
bai = i / 100;
shi = i % 100 / 10;
ge = i % 10;
if (i == (int) Math.pow(bai, 3) + (int) Math.pow(shi, 3) + (int) Math.pow(ge, 3)) {
System.out.println(i);
}
}
}
}

13. Complete the artificial mental retardation system and input how are you? Reply Hello!, Can you understand the input? Reply can understand

public class Demo10 {
public static void main(String[] args) {
//Get input
Scanner sc = new Scanner(System.in);
//Variable declaration type
String question;
while(true){
//Assign the input data to question
question = sc.next();
//The replace() method selects words to replace parameters. One is the string to be replaced and the other is a new string
question = question.replace("Do you","");
question = question.replace("I","Me too");
question = question.replace("？","!");
//output
System.out.println(question);
}
}
}

2, Array

1. Define an integer array nums with a length of 10 and input 10 integers circularly. Then enter an integer, find the integer, find the output subscript, and give a prompt if it is not found.

public class Demo01 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] nums = new int;
for (int i = 0; i < nums.length; i++) {
nums[i] = input.nextInt();
}

//Number of to find
System.out.println("Please enter an integer to find");
int findNum = input.nextInt();

//lookup
for (int i = 0; i < nums.length; i++) {
if (findNum == nums[i]) {
System.out.println("The integer subscript to find is:" + i);
break;
} else if (i == nums.length - 1) {
}
}
}
}

2. Define an integer array nums with a length of 10 and input 10 integers circularly. Output the maximum and minimum values of the array.

public class Demo02 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] nums = new int;
for (int i = 0; i < nums.length; i++) {
nums[i] = input.nextInt();
}

int max = nums;
int min = nums;

for (int i = 0; i < nums.length; i++) {
if (max < nums[i]) {
max = nums[i];
}
if (min > nums[i]) {
min = nums[i];
}
}
System.out.println("The maximum value is:" + max + "，The minimum value is:" + min);
}
}

3. Given an integer array nums and a target value target, please find the two integers with sum as the target value in the array and output their array subscripts. Assuming that each input will only correspond to one answer, you can't reuse the same elements in this array.

public class Demo03 {
public static void main(String[] args) {
int[] nums = {2, 7, 11, 15};
int target = 9;
boolean flag = false;
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
System.out.println("Two numbers satisfying the conditions were found:" + nums[i] + "--" + nums[j] + "The subscript is:" + i + "--" + j);
}
}
}
}
}

4. Sort the array {1, 3, 9, 5, 6, 7, 15, 4, 8}, then use bisection to find element 6, and output the sorted subscript.

public class Demo04 {
public static void main(String[] args) {
//Sort and find
int[] a = {1, 3, 9, 5, 6, 7, 15, 4, 8};
//Store maximum
int temp;
//Sort the input numbers with bubble sort
for (int i = 0; i < a.length - 1; i++) {
for (int j = 0; j < a.length - i - 1; j++) {
if (a[j] > a[j + 1]) {
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}

int f = 6;

//Using binary search
//Minimum boundary subscript
int minIndex = a;
//Maximum boundary subscript
int maxIndex = a.length - 1;
//Middle subscript
int centerIndex = (maxIndex + minIndex) / 2;
while (true) {
if (a[centerIndex] > f) {
//If the intermediate data is large, the maximum range subscript = centerIndex-1
maxIndex = centerIndex - 1;
} else if (a[centerIndex] < f) {
//If the intermediate data is small, the minimum range subscript = centerIndex+1
minIndex = centerIndex + 1;
} else {
//If the intermediate data are equal, the intermediate subscript is output
break;
}

if (minIndex > maxIndex) {
centerIndex = -1;
System.out.println("The number you are looking for does not exist");
}
//When the boundary is updated, the intermediate subscript needs to be updated
centerIndex = (maxIndex + minIndex) / 2;
}
System.out.println("6 Subscript for" + centerIndex);
}
}

5. Given an array num, write a function to move all zeros to the end of the array while maintaining the relative order of non-zero elements. Example: input: [0,1,0,3,12] output: [1,3,12,0,0]

public class Demo05 {
public static void main(String[] args) {
int[] nums = {0, 1, 0, 3, 12};

int[] newNums = moveZero(nums);

for (int i = 0; i < newNums.length; i++) {
System.out.println(newNums[i]);
}
}

public static int[] moveZero(int[] nums) {
int index1 = 0;
int index2 = 0;
//Index 2 does not exceed the length of the array
while (index2 < nums.length) {
//If the element scanned by index 2 is not 0, it moves to the front
if (nums[index2] != 0) {
nums[index1] = nums[index2];
index1++;
index2++;

//A value of 0 allows the index to continue scanning as soon as possible
} else {
index2++;
}
}
//Zero filling
for (int i = index1; i < nums.length; i++) {
nums[i] = 0;
}
return nums;
}
}

3, Object oriented

1. Write a Car class with brand and Color attributes, and define the show method

public class Demo01 {
public static void main(String[] args) {
Car car = new Car();
car.brand = "BMW";
car.Color = "white";
car.show();
}
}

class Car {
String brand;
String Color;

void show() {
System.out.println("The brand of the car is:" + brand + ", The color is" + Color);
}
}

2. Define a game class, including the attributes of the game, including: game name, type, size, star, introduction, etc. you can call methods to output the introduction of the game

public class Demo02 {
public static void main(String[] args) {
Game game = new Game();
game.name = "LOL";
game.type = "5v5";
game.size = "30g";
game.starLevel = "5 Star";

//introduce
game.show();
}
}
class Game {
String name;
String type;
String size;
String starLevel;

void show() {
System.out.println(" The name of the game is:" + name + " The type is:" + type + " Size is" + size + " The stars are:" + starLevel);
}
}

3. Define and test an Employee class representing employees. Its attributes include "Employee name", "Employee number", "Employee basic salary" and "Employee salary growth rate"; His methods include "construction method", "obtaining Employee name", "obtaining Employee number", "obtaining Employee basic salary", "calculating salary increase" and "calculating total salary after increase".

public class Demo03 {
public static void main(String args[]) {
Employee emp = null;
emp = new Employee();
emp.number = "001";
emp.name = "Zhang San";
emp.salary = 1000;
emp.time = 5;
emp.increase();
emp.total();
}

}
class Employee {
String number;
String name;
float salary;
float time;

//growth rate
public void increase() {
System.out.println("Growth=" + "Working years*" + 200);
System.out.println("The increase is" + time * 200);
}

//Total wages
public void total() {
System.out.println("Total wages=base pay+Growth");
System.out.println(salary + time * 200);
}
}

4. It has attributes: name (title) and number of pages (pageNum), in which the number of pages cannot be less than 200, otherwise the error message will be output and the default value of 200 will be given. There are methods: set the assignment and value taking methods for each attribute. Detail is used to output the name and number of pages of each book on the console. Write the test class BookTest to test: give the initial value to the attribute of Demo01.Book object and call the detail of Demo01.Book object L method to see if the output is correct.

public class Book {
//name
private String title;
//the number of pages
private int pageNum;

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public int getPageNum() {
return pageNum;
}

public void setPageNum(int pageNum) {
if (pageNum < 200) {
this.pageNum = 200;
System.err.println("The number of page assignments needs to be greater than 200, which has been assigned as the default 200");
return;
}
}

//Detailed method
public void detail() {
System.out.println("The title of the book is:" + title);
System.out.println("Page number name is:" + pageNum);
}
}
public class BookTest {
public static void main(String[] args) {
Book book = new Book();
book.setTitle("computer");
book.setPageNum(100);

//Display method
book.detail();
}
}
The number of page assignments needs to be greater than 200, which has been assigned as the default 200
The name of the book is: computer
Page name: 200

Process finished with exit code 0

5. Clothes are described by classes. When creating each clothes object, a serial number value needs to be automatically generated. Requirements: the serial number of each garment is different and increases by 1 in turn.

public class Clothes {
private int clothId;
private static int num = 1000;

//Self increasing
public Clothes() {
clothId = num;
num++;
}

public int getClothId() {
return clothId;
}
}
public class ClothesTest {
public static void main(String[] args) {
Clothes clothes1 = new Clothes();
Clothes clothes2 = new Clothes();
Clothes clothes3 = new Clothes();

System.out.println(clothes1.getClothId());
System.out.println(clothes2.getClothId());
System.out.println(clothes3.getClothId());
}
}
1000
1001
1002

Process finished with exit code 0

6. Describe Java students through classes. Have attributes: name, age, gender, hobbies, company (all: start class), discipline (all: Java discipline). Think: Please combine the static modification attribute for better class design.

public class Student {

private String name;
private int age;
private String sex;
private String hobby;

public static String company;
public static String subject;

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 String getSex() {
return sex;
}

public void setSex(String sex) {
this.sex = sex;
}

public String getHobby() {
return hobby;
}

public void setHobby(String hobby) {
this.hobby = hobby;
}

public void show() {
System.out.println("The name is:" + name + " Age is:" + age + " Gender is" + age + " Hobbies are" + hobby);
System.out.println("The company is:" + company + " The disciplines are:" + subject);
}
}
public class StudentTest {
public static void main(String[] args) {
Student student = new Student();
student.setName("Zhang San");
student.setAge(18);
student.setSex("male");

Student.company = "JAVA company";
Student.subject = "java";

Student student1 = new Student();
student1.setName("Li Si");
student1.setAge(20);
student1.setSex("female");
student1.setHobby("Volleyball");

student.show();
student1.show();
}
}
Name: Zhang San age: 18 gender: 18 hobby: basketball
The company is: JAVA The company's disciplines are: java
Name: Li Si age: 20 gender: 20 hobby: volleyball
The company is: JAVA The company's disciplines are: java

Process finished with exit code 0

7. Guessing game:

1. Define the machine class and fist attribute (this attribute has only three values: scissors, stone and cloth. The values here can be replaced by numerical values)
2. Define the method of generating random numbers (let the machine generate the values of scissors, stone and cloth) and assign them to the fist attribute in the first step
3. Define a test class, obtain the value of the shear stone cloth entered by the user, and compare it with the randomly generated value
4. In the test, define variables to save the winner's points
/**
* User class
* @author: JunLog
*/
public class User {
static Scanner input = new Scanner(System.in);
int user = 0;//User punches
int score = 0;//User points
int num = 0;//Number of games

public int setUser() {

user = input.nextInt();

if (user == 1) {
System.out.println("User punch: scissors");
} else if (user == 2) {
System.out.println("User punch: Stone");
} else if (user == 3) {
System.out.println("User punch: cloth");
}
return user;
}
}

/**
* Machine class
* @author: JunLog
*/
public class Robot {
int id = 0;//Get the hand of the robot
int score = 0;//Robot integral

//Get the robot's punch
public int setId() {

Random random = new Random();
int r = random.nextInt(3);
//The reason for obtaining the robot's random punch + 1 is that the random interval does not include 3, which is 0-2
id = r + 1;

if (id == 1) {
System.out.println("Robot punch: scissors");
} else if (id == 2) {
System.out.println("Robot punch: Stone");
} else if (id == 3) {
System.out.println("Robot punch: cloth");
}
return id;
}
}
/**
* Game start class
* Initialize the user and machine class to initialize the game and start making game judgment against the war
* @author: JunLog
*/
public class Game {

User user = new User();
Robot robot = new Robot();

/**
* The game begins
*/
public void GameStart() {
System.out.println("------- Guessing game --------");
System.out.println("--- 1-Scissors 2-Stone 3-cloth--- ");

judge();

showResult();
}

/**
* Win or lose bonus judgment
*/
private void judge() {

Scanner input = new Scanner(System.in);
System.out.println("Enter the number of sessions");
user.num = input.nextInt();
System.out.println("------- The game begins --------");

//Initialize first punch
int userFirst;
int robotFirst;

for (int i = 0; i < user.num; i++) {
//Get both sides to punch
userFirst = user.setUser();
robotFirst = robot.setId();

//judge
if (userFirst == robotFirst) {
System.out.println("The draw integral remains unchanged");
} else if ((userFirst == 2) && (robotFirst == 1) || (userFirst == 3 && robotFirst == 2) ||
(userFirst == 1) && (robotFirst == 3)) {
System.out.println("You win, plus one point");
user.score++;
} else {
System.out.println("You lose, robot plus one point");
robot.score++;
}
}
}

/**
* The results show that
*/
private void showResult() {
//Display the number of battles
System.out.println("------------------------------");
System.out.println("Number of battles:" + user.num);
//Show final score
System.out.println("\n full name\t score");
System.out.println("user" + "\t" + user.score);
System.out.println("robot" + "\t" + robot.score + "\n");
System.out.println("================================");

if (user.score == robot.score) {
System.out.println("result:Draw.");
} else if (user.score > robot.score) {
System.out.println("You win!");
} else {
System.out.println("You lost");
}
System.out.println("game over");
System.out.println("--------------------------");
}
}
/**
* Test class
* @author: JunLog
*/
public class GameTest {
public static void main(String[] args) {
Game game = new Game();
game.GameStart();
}
}
------- Guessing game --------
--- 1-Scissors 2-Stone 3-cloth---
Enter the number of sessions
1
------- The game begins --------
1
User punch: scissors
Robot punch: cloth
You win, plus one point
------------------------------
Number of battles:1

full name	score
user	1
robot	0

================================
You win!
game over
--------------------------

Process finished with exit code 0

public class UserService {

return true;
}
return false;
}
}
/**
* @author: JunLog
*/
public class UserServiceTest {
public static void main(String[] args) {
UserService userService = new UserService();

Scanner input = new Scanner(System.in);

if (result) {
} else {
}
}
}
1

Process finished with exit code 0

123

Process finished with exit code 0

9. Customize a class named MyList, which contains the attribute: Object[] element; The following methods are defined:

1. Add method: you can store objects in the array attribute in turn. When the array is full, you need to realize dynamic capacity expansion (see details below). Reference: Boolean add(Objectobj)
2. Delete method remove: you can delete Object data from the array attribute according to the data or subscript. After deletion, the subsequent elements of the array need to move forward. Reference: void remove(Object obj) or void remove(Integer index)
3. Query method: the get method passes in the subscript and returns the data of the specified subscript in the array. Reference: Object get(Integer index)
4. Current stored data size: get the effective data length currently stored. Reference: size = array Detailed explanation of dynamic capacity expansion of length: without really increasing the capacity of the original array, just copy the original content to the new large array, and then make the name of the original array equal to the large array again. Because the original array data is in the heap, the lost reference will be automatically recycled by GC. (test point: how to realize the dynamic length of an array).
public class MyList {
private Object[] element;
private int capacity;       //capacity
private int size;           //Actual size

public MyList() {
size = 0;
capacity = 4;
//Allocate space for array
element = new Object[capacity];
}

/**
* Delete according to the specified object
* @param obj
* @return
*/
public Object remove(Object obj){
for (int i = 0; i < element.length; i++) {
if (element[i]!=null && obj == element[i]){
return remove(i);
}
}
//There are no objects to delete
return null;
}

/**
* Delete by subscript
* @param index
* @return
*/
public Object remove(int index){
if (index == size-1){
size--;
return element[index];
}
Object obj = element[index];
for (int i = index; i < size; i++) {
element[i] = element[i+1];
}
size--;
return obj;
}

/**
* Query method
* @param index
* @return
*/
public Object get(int index){
return element[index];
}

/**
* @param obj
*/
//Determine whether the array is full
if (size >= capacity) {
//Capacity expansion
Object[] newArr = new Object[capacity * 2];
//Copy the elements of the original array to the new array
for (int i = 0; i < element.length; i++) {
newArr[i] = element[i];
}
//The original array name is redrawn equal to the new array
element = newArr;
}
element[size] = obj;
size++;
}

public int getSize() {
return size;
}
}
/**
* test
* @author: JunLog
*/
public class MyListTest {
public static void main(String[] args) {
MyList list = new MyList();

for (int i = 0; i < 6; i++) {
}

for (int i = 0; i < list.getSize(); i++) {
System.out.println(list.get(i));
}

Object obj = list.remove(2);
System.out.println("The deleted elements are:" + obj);
}
}

java0
java1
java2
java3
java4
java5
The deleted elements are: java2

Process finished with exit code 0

Keywords: Java