java - 在每个 switch-case 之后循环回到开始

标签 java switch-statement

我正在寻找一种在每个案例完成后返回“菜单”的方法,并且仅在选择退出时退出/关闭程序。我假设会使用一个 while 循环,但我无法返回菜单并保持到目前为止的所有输入和进度而无需重新启动程序。到目前为止,这是我的代码;

import java.util.Scanner;

public class User2 {
private static Scanner in;

public static void main(String[] args) {

    in = new Scanner(System.in);

    int userChoice;

    boolean quit = false;
    String firstName = null;
    String secondName = null;
    String email = null;
    String username = null;
    String password = null;

    do {


        System.out.println("1. Create Account");
        System.out.println("2. Login");
        System.out.println("3. Quit");
        userChoice = Integer.parseInt(in.nextLine());

        switch (userChoice) {

        case 1:
            System.out.print("Enter your first name: ");
            firstName = in.nextLine();
            System.out.println("Enter your second name:");
            secondName = in.nextLine();
            System.out.println("Enter your email address:");
            email = in.nextLine();
            System.out.println("Enter chosen username:");
            username = in.nextLine();
            System.out.println("Enter chosen password:");
            password = in.nextLine();

            break;

        case 2:

            String enteredUsername;
            String enteredPassword;

            System.out.print("Enter Username:");
            enteredUsername = in.nextLine();
            System.out.print("Enter Password:");
            enteredPassword = in.nextLine();
            if (username != null && password != null
                    && enteredUsername == username
                    && enteredPassword == password)
                System.out.println("Login Successfull!");
            else
                System.out.println("Login Failed!");

            break;

        case 3:
            quit = true;
            break;
        default:
            System.out.println("Wrong choice.");

        }

        System.out.println();

    } while (!quit);

    System.out.println("Bye!");

  }
}

最佳答案

不要使用 == 进行字符串比较使用 String.equals

例如

enteredUsername.equals (username)

甚至

enteredUsername.equalsIgnoreCase (username)

无论输入的文本大小写如何进行比较

关于java - 在每个 switch-case 之后循环回到开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28976665/

相关文章:

java - 第二个带注释的方面未被调用

Java:有没有一些实用的方法来计算

c - Switch 语句在 C 中不起作用

javascript - switch语句等于===还是==?

python-3.x - 匹配语句 "NaN"

java - 我应该如何从 xml 中的 Apache Jackrabbit 中的节点中提取属性?

java - 如何打开电子邮件客户端并在java中自动附加文件

java - Eclipse部署汇编找不到项目条目

php - Javascript switch 不接受传递的变量

java - 为什么 Java 中的 switch 语句的范围没有限制?