java程序在If语句之后执行Else语句
import java.util.Scanner;
import static java.lang.System.out;
import static java.lang.System.in;
public class AI_Core {
/**
* @param args
*/
public static void main(String[] args) {
String Input;
String HOY_Input;
Scanner Command = new Scanner(in);
Scanner HOY_Response = new Scanner(in);
out.println("Hello Sir, how can I help you?");
while(true){
Input = Command.nextLine();
if((Input.equals("Hello")) || (Input.equals("Hey M"))) {
out.println("Hello Sir, how are you?");
HOY_Input = HOY_Response.nextLine();
if((HOY_Input.equals("Great!")) || (HOY_Input.equals("Alright"))) {
out.println("Glad to hear it sir.");
}
if((HOY_Input.equals("Not so good")) || (HOY_Input.equals("Been better"))) {
out.println("I'm sorry to hear that sir, just let me know if I can help in any way.");
}
}
if(Input.equals("exit")) {
out.println("Goodbye Sir.");
//out.wait();
System.exit(0);
}
else {
out.println("I'm sorry sir, but I don't quite understand the term: ");
out.print(Input);
out.print(", could you please check your spelling and try again?");
}
}
}
}
Else语句在If语句之后执行,如控制台中所示:
Hello Sir, how can I help you?
Hey M
Hello Sir, how are you?
Great!
Glad to hear it sir.
I'm sorry sir, but I don't quite understand the term: Hey M, could you please check your spelling and try again?
# 1 楼答案
当你说
if(Input.equals("exit"))
时,你已经开始了另一个if
。Input
与“exit”不匹配,因此执行else看起来你只想执行三个案件中的一个。在这种情况下,您需要
else if
,将其连接到第一个if
:这样,只有当前两个
if
语句都产生false
时,才会打印I'm sorry sir, but I don't quite understand the term:
# 2 楼答案
问题是您的else语句只引用它前面的if语句。第一个if语句是完全独立的。只要输入不是“退出”,else部分就会执行
您需要一个
else if
来连接所有三条语句,以便只执行一条:此页面可能会有帮助:
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html