我是java的初学者,我最近才开始学习接口,所以我试着编写一个程序,其中包含实现整数的类。无论如何,我的程序中的while循环遇到了问题。我想让用户有机会在与知更鸟或人交谈之间做出选择,据我所知,&&会检查这两种情况(如果这两种条件都是真的,则运行循环)。
import java.util.Scanner;
public class App {
public static void main(String[] args) {
Scanner ai = new Scanner(System.in);
Conversation guy = new Human();
Conversation rox = new Robot();
System.out.println("What do you want to talk to?");
String choice = ai.nextLine();
while (choice != "Robot" && choice!= "Person"){
System.out.println("Option not available, choose again.");
choice = ai.nextLine();
}
switch(choice){
case "Person":
System.out.println("What's my name?");
guy.greet();
guy.conv();
guy.bye();
break;
case "Robot":
System.out.println("What's my name?");
rox.greet();
rox.conv();
rox.bye();
break;
}
ai.close();
}
}我尝试这样做,以便如果输入既不是"Person"也不是"Robot",它会再次扫描新输入,但是尽管输入不是输入,程序总是运行循环,为什么?
发布于 2015-04-19 19:09:15
您正在使用String比较对象( == ),它在这里比较引用:
choice != "Robot" && choice!= "Person"您需要使用.equals()方法来有意义地比较字符串
https://stackoverflow.com/questions/29734515
复制相似问题