关闭。这个问题需要细节或清晰。它目前不接受答案。
**想改进这个问题吗?**通过编辑这个帖子来添加细节并澄清问题。
三年前关门了。
改进这个问题
下面是代码。如果我在arraylist中输入了第二个bird,我不明白为什么在类数据库中else if状态与if语句同时运行。求求你,任何帮助都将不胜感激!
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Database d1 = new Database();
while (true) {
System.out.println("What do you want to do?");
String answer = input.nextLine();
if(answer.equalsIgnoreCase("Add")){
System.out.println("Name: ");
String name = input.nextLine();
System.out.println("Latin name: ");
String lName = input.nextLine();
d1.addBird(name, lName);
} else if (answer.equalsIgnoreCase("O")) {
System.out.println("What was observed?");
String observed = input.nextLine();
d1.Observation(observed);
} else if (answer.equalsIgnoreCase("stats")) {
d1.showBirds(); //Displays all with observations.
} else if (answer.equalsIgnoreCase("show")) {
System.out.println("What?");
String search = input.nextLine();
d1.searchBird(search);
} else if (answer.equalsIgnoreCase("quit")){
break;
}
}
}
}
public class Bird {
private final String name;
private final String latinName;
private int count;
public Bird (String name, String latinName) {
this.name = name;
this.latinName = latinName;
this.count = count;
}
public String getName () {
return this.name;
}
public String getLatin() {
return this.latinName;
}
public String add () {
return this.name + " " + "(" +this.latinName + ")"+ " " + this.count + " observation(s)";
}
public void increaseCount () {
this.count++;
}
}
import java.util.ArrayList;
public class Database {
private final ArrayList<Bird> birdList;
public Database() {
this.birdList = new ArrayList<Bird>();
}
public void addBird (String name, String lname) {
this.birdList.add(new Bird(name, lname));
}
public void Observation (String observed) {
for (Bird x : getBirds()) { // this has to be a method
if (x.getName() != null && x.getLatin() != null && x.getName().contains(observed) || x.getLatin().contains(observed)) {
System.out.println("Done");
System.out.println("");
x.increaseCount();
} else if (x.getName() != observed || x.getLatin() != observed) {
System.out.println("Not a bird");
}
}
}
public void showBirds () {
for (Bird x : this.birdList) {
System.out.println(x.add());
}
}
public ArrayList<Bird> getBirds() {
return this.birdList;
}
public void searchBird(String search) {
for (Bird x : getBirds()) {
if (x.getName().contains(search)) {
System.out.println(x.add());
}
}
}
}
1条答案
按热度按时间neskvpey1#
我认为问题在于这种方法:
这样做: