有十只小狗,被小明随机收养了三只,打印出狗的名字
Dog类
public class Dog {
String name;
}
Market类
public class Market {
Dog [] dogs = new Dog[10];
//初始化代码段,只为初始化数组
{
for (int i=0;i< dogs.length;i++)
{
dogs[i] = new Dog();
dogs[i].name = "Dog"+(i+1);
}
}
}
Person类
import java.util.Arrays;
public class Person {
String name = "小明";
Market m = new Market();
Dog [] arr = new Dog[3];
public void getDog()
{
for (int i=0;i< arr.length;i++)
{
int id;
do {
id = (int) (Math.random()*10);
}
while (m.dogs[id] == null);
arr[i] = m.dogs[id];
m.dogs[id] = null;//清空市场中的🐶
}
}
public void show()
{
System.out.println("本次买狗如下:");
System.out.println(this.name);
//对于for(类型名 类型 : 需要遍历的数组),这时候就是先创建了对象或者变量,然后遍历数组,一个一个赋值给类型类型:可以是变量,对象
for (Dog dog : arr)
{
System.out.println(dog.name);
}
}
}
Test类
public class Test {
public static void main(String[] args) {
Person p = new Person();
p.name = "老王";
p.getDog();
p.show();
}
}
5469

被折叠的 条评论
为什么被折叠?



