while 循环检查两个布尔值总是运行
while loop checking for two booleans always runs
我是 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"
,它会再次扫描新输入,但尽管输入是其中之一,程序总是运行循环,为什么?
您正在使用 ==
比较对象 (String
),它在此处比较引用:
choice != "Robot" && choice!= "Person"
您需要使用 .equals()
方法来有意义地比较字符串
我是 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"
,它会再次扫描新输入,但尽管输入是其中之一,程序总是运行循环,为什么?
您正在使用 ==
比较对象 (String
),它在此处比较引用:
choice != "Robot" && choice!= "Person"
您需要使用 .equals()
方法来有意义地比较字符串