在每个开关盒之后循环回来开始

时间:2015-03-11 00:44:55

标签: 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!");

  }
}

2 个答案:

答案 0 :(得分:2)

请勿使用==进行字符串比较,使用String.equals

e.g。

enteredUsername.equals (username)

甚至

enteredUsername.equalsIgnoreCase (username)

用于比较,无论输入文本的情况如何

答案 1 :(得分:1)

我尝试运行您的代码,但在创建帐户后我无法登录。仔细查看if语句,比较用户名和密码,我注意到你正在使用==比较字符串 字符串通常是任何面向对象语言的对象,因此在java中你需要使用

enteredUsername.equals(username)

并对要比较的任何其他字符串使用相同的方法。还有其他字符串比较方法,如果查看字符串类,可以在oracle的java文档中找到有关它们的更多信息。对于您现在正在使用的代码,.equals可能就是您要使用的代码。