提供属性时遍历对象

时间:2020-01-25 17:09:51

标签: java loops object attributes

我知道我的代码没有意义,我只是在学习,并且这样做是为了进行for循环。请参阅Main中的评论!当我使用基本的for循环时,名称会失去“ .gender”功能!寻求帮助!

public class Dog {


public String whatGender(String gender) {
    if (gender == "yes") {
        gender = "Male";
    } else {
        gender = "Female";
    }
    return gender;
}


public class Main {

public static void main (String[] args) {
    Dog Kvist = new Dog("Vuf!", 8, "yes");
    Dog Snoop = new Dog("Doggy Dogg World!", 48, "yes");
    Dog Greta = new Dog("We need change now!", 17, "no");

    //How do I translate the next 3 lines to a for-loop? #StillLearning
    Kvist.gender = Kvist.whatGender(Kvist.gender);
    Snoop.gender = Snoop.whatGender(Snoop.gender);
    Greta.gender = Greta.whatGender(Greta.gender);

2 个答案:

答案 0 :(得分:0)

一种方法是创建一个Dog数组,然后使用for循环遍历它们:

public static void main (String[] args) {
    Dog Kvist = new Dog("Vuf!", 8, "yes");
    Dog Snoop = new Dog("Doggy Dogg World!", 48, "yes");
    Dog Greta = new Dog("We need change now!", 17, "no");

    Dog[] dogs = {Kvist, Snoop, Greta};

    //How do I translate the next 3 lines to a for-loop? #StillLearning
    for (int i = 0; i < dogs.length; i++)
    {
        dogs[i].gender = dogs[i].whatGender(dogs[i].gender);
    }
    // Kvist.gender = Kvist.whatGender(Kvist.gender);
    // Snoop.gender = Snoop.whatGender(Snoop.gender);
    // Greta.gender = Greta.whatGender(Greta.gender);

答案 1 :(得分:0)

至少缺少gender的实例变量Dog
并且whatGender方法可以重新编码:

public String whatGender(final String gender) {
    if (gender == "yes") {
        return "Male";
    } else {
        return "Female";
    }
}

...我很想知道您要使用该方法实现什么?

但是无论如何,只要回答“原样”问题,您就可以做到:

Stream.of(Kvist, Snoop, Greta).forEach(dog -> dog.gender = dog.whatGender(dog.gender));

...但是那里有太多dog.gender