Java 构造函数输入验证使用while循环不工作

Java 构造函数输入验证使用while循环不工作,java,while-loop,java.util.scanner,equals,composition,Java,While Loop,Java.util.scanner,Equals,Composition,我试图使用构造函数中提供的验证检查来初始化类Animal的实例字段。如果我在调用构造函数时输入了正确的值(例如tiger),它似乎会起作用,但如果我在输入了错误的值后输入了相同的值,它就不起作用了。出于某种原因,它似乎没有退出while循环。我正在使用composition测试字段值是否输入正确 公营动物{ 私有字符串类型 public Animal(String type) { enter code here if ((type.equals("cheetah

我试图使用构造函数中提供的验证检查来初始化类Animal的实例字段。如果我在调用构造函数时输入了正确的值(例如tiger),它似乎会起作用,但如果我在输入了错误的值后输入了相同的值,它就不起作用了。出于某种原因,它似乎没有退出while循环。我正在使用composition测试字段值是否输入正确

公营动物{ 私有字符串类型

    public Animal(String type) {
    enter code here

        if ((type.equals("cheetah")) || (type.equals("tiger")) || (type.equals("Snake")) || (type.equals("lion"))) {
            this.type = type;
        }
        else  {
            Scanner animaltype = new Scanner(System.in);
            System.out.println("This animal has either left the jungle or is not present in the jungle. Please enter another value.");
            type = animaltype.next();
            while ((!type.trim().equals("cheetah") || (!type.trim().equals("tiger")) || (!type.trim().equals("Snake")) || (!type.trim().equals("lion"))))
                     {
                if (type.equals("kangaroo")) {
                    System.out.println("Kangaroos have left the jungle. Please enter another value");
                    type = animaltype.next();
                }
               else if ((!type.trim().equals("kangaroo")) || (!type.trim().equals("cheetah")) || (!type.trim().equals("tiger")) || (!type.trim().equals("Snake")) || (!type.trim().equals("lion"))) {
                    System.out.println("This animal is not present in the Jungle. Please enter another value");
                    type = animaltype.next();
                }


            }
            this.type = type;
        }
        }



    public String getType() {
        return this.type;
    }
}

public class main {
    public static void main(String[] args) {
        Scanner animaltype = new Scanner(System.in);
        System.out.println("Store the type of animal that is in the jungle");

        String rt = animaltype.next();
        Animal animal = new Animal(rt);
        Jungle jungle = new Jungle(animal);

        System.out.println(jungle.getAnimal().getType());
    }
}

public class Jungle {
    private Animal animal;


    public Jungle(Animal animal) {
        this.animal = animal;

    }

    public Animal getAnimal() {
        return animal;
    }
}

while
循环中的条件不正确。它表示,如果
type
不等于至少一个字符串,则继续。嗯,
type
不能等于这些字符串中的多个,因此while循环将永远继续。发生这种现象的原因是您正在使用
,并且需要e使用
运算符。您需要将条件替换为
(!type.trim().equals(“猎豹”)&(!type.trim().equals(“老虎”)&(!type.trim().equals(“蛇”)&(!type.trim().equals(“狮子”)
,或者替换为
!(type.trim().equals(“猎豹”)| type.trim().equals(“老虎”)| type.trim().equals(“蛇”)| | type.trim().equals(“lion”)
。两者都表示如果
type
等于任何字符串,则退出
while
循环

PS:
trim()
是不需要的,因为
Scanner
next
方法返回下一个标记,这基本上意味着下一个单词,因此
type
将被修剪