【问题标题】:Both branches are being executed in my if-else statement两个分支都在我的 if-else 语句中执行
【发布时间】:2015-11-05 12:19:53
【问题描述】:

当我要求教员输入时,它会正确执行,直到输出被打印,然后它会打印 ask for the 800 number(仅对学生询问)。我不明白为什么在你输入教师后它总是询问学生的具体问题。

    public class UniversityIDApp {
public static void main(String[] args){
    // display a welcome message
    System.out.println("Welcome to the University ID application");
    System.out.println();

    Scanner sc = new Scanner(System.in);
    String choice = "y";
    while(choice.equalsIgnoreCase("y"))
    {
        // get user entries
        String userType = Validator.getString(sc,
            "Create student or faculty? (s/f):   ", "s", "f");
        String firstName = Validator.getString(sc,
            "Enter first name:   ");
        String lastName = Validator.getString(sc,
            "Enter last name:   ");
        String email = Validator.getString(sc,
            "Enter e-mail:  ");


    if (userType.equalsIgnoreCase("f"))
    {

    String department = Validator.getString(sc,
            "Enter department:   ");

       // create faculty object
       Faculty f = new Faculty() {};
       f.setFirstName(firstName);
       f.setLastName(lastName);
       f.setEmail(email);
       f.setDepartment(department);
       System.out.print("Southern Illinois University Faculty ");
       System.out.print("\nName:       " + f.getFirstName() + " " + f.getLastName() + "\n" 
       +  "Email:      "  + f.getEmail() + "\n" + "Department: " + f.getDepartment() + "\n" );
       System.out.println();
    }
    else if(userType.equalsIgnoreCase("s"));
    {

    Student s = new Student() {};
    String student800Number = Validator.getString(sc,
            "Enter your 800 number:   ");

       s.setFirstName(firstName);
       s.setLastName(lastName);
       s.setEmail(email);
       s.setStudent800Number(student800Number);
       System.out.print("Southern Illinois University Student");
       System.out.print("\nName:        " + s.getFirstName() + " " + s.getLastName() + "\n" 
  +   "Email:       "  + s.getEmail() + "\n" + "Student 800 Number:  " + s.getStudent800Number() + "\n" );
       System.out.println();

        }
        System.out.print("Continue? (y/n): ");
        choice = sc.next();
        System.out.println();
    }
}

【问题讨论】:

标签: java if-statement


【解决方案1】:

你的 else if 子句有一个分号 ; 使它什么都不做。

...
}
   else if(userType.equalsIgnoreCase("s")); //<-- here
{
...

与此相同:

        if ( true ) {
            System.out.println("true");
        } else if ( false ) {
            ;
        }

        {
            System.out.println("false? what's going on?");
        }

如果您将左大括号放在同一行(这是 Java 的约定),这可能会更容易发现

【讨论】:

    猜你喜欢
    • 2022-12-14
    • 1970-01-01
    • 2016-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-20
    • 1970-01-01
    相关资源
    最近更新 更多