我的程序应该打印出所有3岁以上爪子的猫的名字和年龄。对于以下输入
Enter the name of Cat 1: Sam
Enter the age of Cat 1: 1
Enter the weight of Cat 1: 5
Enter the breed of Cat 1: fluffy1
Does the cat have claws? True or False?: True
Enter the name of Cat 2: Tom
Enter the age of Cat 2: 4
Enter the weight of Cat 2: 5
Enter the breed of Cat 2: fluffy2
Does the cat have claws? True or False?: True
Enter the name of Cat 3: Bob
Enter the age of Cat 3: 5
Enter the weight of Cat 3: 5
Enter the breed of Cat 3: fluffy3
Does the cat have claws? True or False?: False
输出应该是这样的。
The Cats over 3 with claws are:
Name: Tom
Age: 4 Years Old
然而,程序完成没有输出。这是我执行的代码。
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class MyClass {
private static Cat[] catArray = new Cat[3];
public static void main(String[] args) throws IOException {
for (int i=0;i<3;i++) {
Cat cat = new Cat();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the Name of Cat " + (i+1) + ": ");
cat.setName(in.readLine());
System.out.print("Enter the Age of Cat " + (i+1) + ": ");
cat.setAge((Integer.parseInt(in.readLine())));
System.out.print("Enter the Weight of Cat " + (i+1) + ": ");
cat.setWeight((Double.parseDouble(in.readLine())));
System.out.print("Enter the Breed of Cat " + (i+1) + ": ");
cat.setBreed(in.readLine());
System.out.print("Does the cat have claws? True or False: ");
String hasClaws = in.readLine();
if(hasClaws.equals("False"))
cat.sethasClaws(false);
else
cat.sethasClaws(true);
catArray[i] = cat;
}
for(int j=0;j<3;j++) {
if((catArray[j].getAge()>=3) && (!catArray[j].hasClaws()) ) {
System.out.println("The cats over 3 with claws are: \n");
System.out.println("Name: " + catArray[j].getName());
System.out.println("Age: " + catArray[j].getAge() + " years old");
}
}
}
}
还有:
public class Cat {
private String name;
private int age;
private double weight;
private String breed;
private boolean hasClaws;
public Cat() {}
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 double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public String getBreed() {
return breed;
}
public void setBreed(String breed) {
this.breed = breed;
}
public boolean hasClaws() {
return hasClaws;
}
public void sethasClaws(boolean hasClaws) {
this.hasClaws = hasClaws;
}
}
答案 0 :(得分:2)
我相信!
中的(catArray[j].getAge()>=3) && (!catArray[j].hasClaws())
运算符会弄乱你。这等同于向我展示3只或以上的猫,它们没有爪子#34;
来自:https://docs.oracle.com/javase/tutorial/java/nutsandbolts/opsummary.html
!逻辑补码算子; 反转布尔值
试试这个:
for(int j=0;j<3;j++) {
if((catArray[j].getAge()>=3) && (catArray[j].hasClaws()) ) {
System.out.println("The cats over 3 with claws are: \n");
System.out.println("Name: " + catArray[j].getName());
System.out.println("Age: " + catArray[j].getAge() + " years old");
}
}