Java Scanner输入事故

时间:2016-07-22 03:49:00

标签: java java.util.scanner

所以我有这个程序接收用户的输入并检查它是否适合成为他们的密码。为了合适,输入必须至少8个字符长,仅包含数字和字母,并且至少包含2个数字。我还必须加入一些异常处理,因此如果输入不适合作为密码,程序将显示相应的错误消息并返回到输入提示阶段。但是如果密码有效,程序需要向用户发出提示,要求他们关闭或重新运行整个程序。

我所做的是在更大的while循环中创建一个do while循环,程序运行完美,用于捕获无效输入并显示相应的错误消息,但我意识到重复整个程序提示出现并且用户按下1要重新运行该程序,用户密码输入的提示将读入该1并将其显示为无效密码。我需要弄清楚如何在重新运行程序输入中确保我的密码提示doe snot read。我的代码如下:

       import java.util.Scanner;
       public class Ed10Chp6Ex6Point18CheckPasswordProgram {

public static void main(String[] args) {
    System.out.println("This program will...");

    Scanner input = new Scanner(System.in);
    int repeatInt = 1;
    boolean Continue = true;

    while(repeatInt == 1){
        do {
        System.out.println("Please enter a password that....");
        String password = input.nextLine();

        if(checkPassword(password) == "Congradulations, the password you have entered is valid!"){
            System.out.println(checkPassword(password));
            Continue = false;
        }
        else{
            System.out.println(checkPassword(password));
            Continue = true;
        }

        } while (Continue);

    System.out.println("To repeat the program enter 1 for yes or 0 for no");
    repeatInt = input.nextInt();
    }   
    }

//check password method
public static String checkPassword(String x) {

        String errorMessage = "Congradulations, the password you have entered is valid!";

        //must have at least eight characters
        if (x.length() < 8){
            errorMessage = "The password you entered is invalid, password must be at least 8 characters";
            return errorMessage;
            }

        //consists of only letters and digits
        for (int i = 0; i < x.length(); i++) {
            if (!Character.isLetter(x.charAt(i)) && !Character.isDigit(x.charAt(i))) {
                errorMessage = "The password you entered is invalid, password must contain only letters and digits";
                  return errorMessage;
              }
            }

            //must contain at least two digits
            int count = 0;
            for (int i = 0; i < x.length(); i++) {
              if (Character.isDigit(x.charAt(i))){
                count++;
              }
            }

            if (count >= 2){
              return errorMessage;
            }
            else {
                errorMessage = "The password you entered is invalid, password must contain at least two digits";
              return errorMessage;
            }
    }
}

非常感谢任何帮助!

0 个答案:

没有答案