【需求】:编写程序,记录3只流浪猫的姓名、性别、花色和状况信息,并通过不同的遍历方式输出小猫信息。3只流浪猫的详细信息如下: 【思路】: 1. 定义类 猫; 2.创建3个流浪猫对象; 3.将对象存储到List集合中(使用多态); 分别使用迭代器、foreach、for循环将List集合信息
时间: 2023-06-27 21:05:16 浏览: 373
输出。
以下是示例代码:
```java
import java.util.*;
public class Cat {
private String name;
private String gender;
private String color;
private String status;
public Cat(String name, String gender, String color, String status) {
this.name = name;
this.gender = gender;
this.color = color;
this.status = status;
}
public String getName() {
return name;
}
public String getGender() {
return gender;
}
public String getColor() {
return color;
}
public String getStatus() {
return status;
}
public void printInfo() {
System.out.println("Name: " + name);
System.out.println("Gender: " + gender);
System.out.println("Color: " + color);
System.out.println("Status: " + status);
}
}
public class Main {
public static void main(String[] args) {
Cat cat1 = new Cat("Tom", "Male", "White", "Healthy");
Cat cat2 = new Cat("Jerry", "Female", "Black", "Sick");
Cat cat3 = new Cat("Luna", "Female", "Gray", "Missing");
List<Cat> cats = new ArrayList<>();
cats.add(cat1);
cats.add(cat2);
cats.add(cat3);
System.out.println("Using Iterator:");
Iterator<Cat> iterator = cats.iterator();
while (iterator.hasNext()) {
Cat cat = iterator.next();
cat.printInfo();
System.out.println();
}
System.out.println("Using For-each:");
for (Cat cat : cats) {
cat.printInfo();
System.out.println();
}
System.out.println("Using For Loop:");
for (int i = 0; i < cats.size(); i++) {
Cat cat = cats.get(i);
cat.printInfo();
System.out.println();
}
}
}
```
运行结果如下:
```
Using Iterator:
Name: Tom
Gender: Male
Color: White
Status: Healthy
Name: Jerry
Gender: Female
Color: Black
Status: Sick
Name: Luna
Gender: Female
Color: Gray
Status: Missing
Using For-each:
Name: Tom
Gender: Male
Color: White
Status: Healthy
Name: Jerry
Gender: Female
Color: Black
Status: Sick
Name: Luna
Gender: Female
Color: Gray
Status: Missing
Using For Loop:
Name: Tom
Gender: Male
Color: White
Status: Healthy
Name: Jerry
Gender: Female
Color: Black
Status: Sick
Name: Luna
Gender: Female
Color: Gray
Status: Missing
```
阅读全文