【问题标题】:How to deny switch-case running unless variable initialized除非变量初始化,否则如何拒绝 switch-case 运行
【发布时间】:2015-03-10 22:31:21
【问题描述】:

我正在创建一个非常基本的登录系统来测试 switch-case,但是我遇到了一个问题,即除非初始化变量,否则 case 2 无法运行。在我的程序中,案例 1 是创建帐户,案例 2 是登录帐户。但是,案例 2 可以立即访问,但除非已创建帐户的详细信息,否则不会运行。我正在寻找一种拒绝访问案例 2 的方法,除非案例 1 已首先完成。这可能吗?这是我的登录系统;

public class User {

private static Scanner in;

public static void main(String[] args) {

    in = new Scanner(System.in);

    int userChoice;

    boolean quit = false;

    do {

        System.out.println("1. Create Account");

        System.out.println("2. Login");

        System.out.print("3. Quit");

        userChoice = in.nextInt();

        switch (userChoice) {

        case 1:

            String firstName;
            String secondName;
            String email;
            String username;
            String password;

            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 (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.");

            break;

        }

        System.out.println();

    } while (!quit);

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

  }
}

我目前收到此错误;

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
The local variable username may not have been initialized
The local variable password may not have been initialized

at User.main(User.java:68)

【问题讨论】:

  • 如果用户先输入 2 会发生什么?
  • 可以尝试登录,但用户没有登录凭据。
  • 要做的第一件事:在编译之前不要尝试运行您的代码!
  • 这段代码让我很困惑...为什么不将其更改为 if...else if... 语句,并使用布尔值控制他们是否已创建帐户。
  • 记录“案例 1”的变量已经运行,并且如果没有运行 if 语句来防止“案例 2”?这真的需要成为堆栈溢出问题吗?

标签: java variables switch-statement


【解决方案1】:

首先,您需要在while 循环之外声明您的帐户变量,否则每次while 循环运行时它们都会重新初始化。

其次,您可以先手动将变量初始化为null,然后检查情况2。

最后,您正在混合使用nextInt()nextLine(),这将导致扫描仪出现一些奇怪的用户界面问题。这是一个更正的版本。

也不要使用 == 比较字符串。

import java.util.*;

public class User {
    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.equals ( username) && enteredPassword.equals (password))
                        System.out.println("Login Successfull!");
                    else
                        System.out.println("Login Failed!");

                    break;

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

            System.out.println();

        } while (!quit);

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

    }
}

【讨论】:

  • 最后,不要将用户名和密码与 == 进行比较,而是使用输入的用户名.equals(用户名) && 输入的密码.equals(密码),否则我很快就会看到另一个 StackOverflow 问题!
【解决方案2】:

你的范围有问题。

所以你有:

case 1:

    String firstName;
    String secondName;
    String email;
    String username;
    String password;

问题是,案例 2:在案例 1:中看不到用户名:因为它无法获取。所以你应该在 switch 语句之前声明这些,这样你的代码就会变成这样:

do {

        System.out.println("1. Create Account");

        System.out.println("2. Login");

        System.out.print("3. Quit");

        userChoice = in.nextInt();
        String firstName ="";
        String secondName ="";
        String email ="";
        String username ="";


        String password ="";

        switch (userChoice) {
    case 1:

您会注意到我还在字符串中添加了一个 = "",因为即使它们为空,您也应该始终初始化它们。

字符串现在在 switch 语句之外声明,因此它们现在可以被 switch 语句中的所有内容访问。

希望对您有所帮助。

【讨论】:

    【解决方案3】:

    正如编译器所说,您需要初始化一个局部变量,但主要问题是您必须在 switch 块之外声明这些变量。并至少将其初始化为 null 或 ""。

    import java.util.Scanner;
    public class User {
    
    private static Scanner in;
    
    public static void main(String[] args) {
    
        in = new Scanner(System.in);
    
        int userChoice;
    
        boolean quit = false;
    
        do {
    
            System.out.println("1. Create Account");
    
            System.out.println("2. Login");
    
            System.out.print("3. Quit");
    
            userChoice = in.nextInt();
    
            String username = null;  // MOVE HERE -------------
            String password = null;
    
            switch (userChoice) {
    
            case 1:
    
                String firstName;
                String secondName;
                String email;
    
                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 (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.");
    
                break;
    
            }
    
            System.out.println();
    
        } while (!quit);
    
        System.out.println("Bye!");
    
    }
    

    }

    【讨论】:

      【解决方案4】:

      请尝试以下代码。在 switch 之外声明变量将起作用

      import java.util.Scanner;
      
      public class User {
      
      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;
      
      String enteredUsername = null;
      String enteredPassword = null;
      
      do {
      
          System.out.println("1. Create Account");
      
          System.out.println("2. Login");
      
          System.out.print("3. Quit");
      
          userChoice = in.nextInt();
      
          switch (userChoice) {
      
          case 1:
      
              System.out.print("Enter your first name: ");
      
              do {
                  firstName = in.nextLine();               
      
              }while(firstName == null || firstName.equals(""));
      
      
              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:
              System.out.print("Enter Username:");
      
              do {
                  enteredUsername = in.nextLine();                
      
              }while(enteredUsername == null || enteredUsername.equals(""));
      
              System.out.print("Enter Password:");
      
              enteredPassword = in.nextLine();
      
              if (enteredUsername.equals(username) && enteredPassword.equals(password)) {
      
                  System.out.println("Login Successfull!");
              }
      
              else
      
                  System.out.println("Login Failed!");
      
              break;
      
          case 3:
      
              quit = true;
      
              break;
      
          default:
      
              System.out.println("Wrong choice.");
      
              break;
      
          }
      
          System.out.println();
      
      } while (!quit);
      
      System.out.println("Bye!");
      
       }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-05-12
        • 1970-01-01
        • 2013-05-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-28
        • 2019-05-17
        相关资源
        最近更新 更多