问题描述
我在使用Java解决这个基本问题时遇到了麻烦。 我有一组5个动物笼子,每个笼子都有一个ID。 当我尝试验证笼子中是否已经包含动物时,检查仅适用于前2个笼子,之后的任何东西都是马车。
这是主要的:
Cat picasso = new Cat ("Cat", "Picasso");
Cat athena = new Cat("Cat", "Athena");
Dog thunder = new Dog ("Dog", "Thunder");
Dog buffy = new Dog("Dog", "Buffy");
Pets store = new Pets("Super store");
store.addToCage(buffy, 1);
store.addToCage(athena, 1);
这会抛出一条错误信息:“笼子已满”
但这个没有:
store.addToCage(buffy, 1);
store.addToCage(athena, 2);
store.addToCage(thunder, 2);
它打印消息(笼子已满),但它仍然将动物添加到笼子2中。任何超过2个笼子都有问题:例如,它打印第三个笼子两次。
这是方法中的addToCage方法
class Pets {
ArrayList<Cage> cages = new ArrayList<Cage>();
public void addToCage(Animal animal, int cageId){
int nbrCages = cages.size();
Cage tmp, cage;
if(nbrCages == 0){
cage = new Cage(cageId);
cage.setAnimal(animal);
this.cages.add(cage);
}else{
for(int i=0; i < nbrCages; i++){
tmp = cages.get(i);
if(tmp.getId() == cageId){
System.out.println("cage is full");
}else{
cage = new Cage(cageId);
cage.setAnimal(animal);
this.cages.add(cage);
这是打印结果的方法:
public String displayResults(){
String results="";
int nbrCages = cages.size();
if(nbrCages > 0){
Cage tmp;
for(int i=0; i < nbrCages; i++){
tmp = cages.get(i);
results += tmp.showCages();
}
}else{
results += "store is empty";
}
return results;
}
1楼
你的问题是else
语句。
你应该做这样的验证:
public void addToCage(Animal animal, int cageId) {
int nbrCages = cages.size();
Cage tmp, cage;
if (nbrCages == 0) {
cage = new Cage(cageId);
cage.setAnimal(animal);
this.cages.add(cage);
} else {
boolean cageInUse = false;
for (int i = 0; i < nbrCages; i++) {
tmp = cages.get(i);
if (tmp.getId() == cageId) {
System.out.println("cage is full");
cageInUse = true;
break;
}
}
if (!cageInUse) {
cage = new Cage(cageId);
cage.setAnimal(animal);
this.cages.add(cage);
}
}
}
这不是最好的解决方案,但它可以解决您的问题。
2楼
这是你刚检查笼子是否为空的问题nbrCages == 0
但是笼子是否有空间。
如果动物出现tmp.getId() == cageId
你只是印刷cage is full
改变它对animal is present in cage
public void addToCage(Animal animal, int cageId){
int nbrCages = cages.size();
Cage tmp, cage;
if(nbrCages < 2){ // First check the cage have space or not
for(int i=0; i < nbrCages; i++){
tmp = cages.get(i);
if(tmp.getId() == cageId){ // Now check animal present in cage or not, if present don't add
System.out.println(" Animal already present in cage ");
}else{ // If not present the add the animal to cage
cage = new Cage(cageId);
cage.setAnimal(animal);
this.cages.add(cage);
}else{ // If not print cage is full
System.out.println(" cage is full on animals ");
}