有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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?


共 (2) 个答案

  1. # 1 楼答案

    当你说if(Input.equals("exit"))时,你已经开始了另一个ifInput与“exit”不匹配,因此执行else

    看起来你只想执行三个案件中的一个。在这种情况下,您需要else if,将其连接到第一个if

    else if(Input.equals("exit")) {
    

    这样,只有当前两个if语句都产生false时,才会打印I'm sorry sir, but I don't quite understand the term:

  2. # 2 楼答案

    问题是您的else语句只引用它前面的if语句。第一个if语句是完全独立的。只要输入不是“退出”,else部分就会执行

    您需要一个else if来连接所有三条语句,以便只执行一条:

    else if(Input.equals("exit")) {
    

    此页面可能会有帮助:

    http://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html