English 中文(简体)
Simple JAVA: Password Verifier problem
原标题:

I have a simple problem that says:

A password for xyz corporation is supposed to be 6 characters long and made up of a combination of letters and digits. Write a program fragment to read in a string and print out a message as to whether or not the string entered would be considered a valid password.

I need help on completing this code. I have this pseudocode that I can t workout into Java code:

print "enter new password"
input newPassword
digitCounter =0
letterCounter = 0
for I = 0 to newPassword.length() by 1
    c = newPassword.charAt(i)
    if c is a digit
        increment digitCounter
    else if c is a letter
        increment letterCounter
    endif
endFor
if newPassword.length() >= 6 and digitCounter > 0 and letterCounter > 0
    print "the password is valid"
else
    print " password rejected, must be at least 6 characters long and be a mix of letters and digits "
endif

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

So far all I have is this for the Java code:

import java.util.Scanner;

public class Password 
{
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);

        String thePassword;

        int len, i, letterCounter = 0, digitCounter = 0;
        char c;

        Len = thePassword.length();

        System.out.print("Enter the password: ");
        thePassword = in.nextLine();

        for (i = 0,i = len, )
        {
            c = in.charAt(1);

            if ()
        }

    }
}
最佳回答

Take a look at Character.isDigit() and Character.isLetter() for checking the characters:

If you want to use String.charAt() to get the characters of your string, you could do a for loop like so:

for (int i = 0;i < s.length();i++) {
    char c = s.charAt(i);
    //Check things about c
}

Although Java 1.5 instroduced a For-Each loop which will loop automatically over arrays like so:

for (char c : s.toCharArray()) {
    //Check things about c
}
问题回答
impot javax.swing.JOptionPane;
class PasswordDemo{
  public static void main(String[] agrs){
     String pass = "abcdef";
     String right = "Success!";
     String wrong = "Failed to login";
     String input = JOptionPane.showInputDialog("Enter the password to login: ");

     do{
        JOptionPane.showMessageDialog(null,wrong);
        input = JOptionPane.showInputDialog("Enter the password to login: ");
     }while(!input.equals(pass));
     //when login successfully
     JOptionPane.showMessageDialog(null,right);
   }
}

I d check that the Regex d (any digit), and the Regex [a-z] (any letter) both matches the string. And then check for length.

A couple quick tips:

  • your pseudo code algorithm is not correct. It will correctly validate that strings must indeed be at least 6 characters in length, but won t invalidate passwords with weird characters in them (e.g. ~%). Based on the problem statement, it seems implicit that the sentence "made up of a combination of letters and digits" means made up only of those. For this part, as others have mentionned, you can use built-in methods of the String or Character classes such as String.charAt(), Character.isDigit() and Character.isLetter().

  • make it a habit to declare stuff at the latest possible time (i.e just before it s used). In your example, you have String thePassword, then 2 other lines, then you assign something to thePassword. Instead, write it directly as String thePassword = in.nextLine(). This will help make the code less cluttered and easier to read. Same for your other declarations (char c, int len, etc.).

  • try to use the enhanced for loop if you can, in order to avoid having to figure out the length and determine where to stop (potential for errors). In your example, your loop could be something like for (char c : thePassword.toCharArray()). If you haven t talked about this loop in your class yet, you don t have to use, and you should know how the simple for loop works as well, but this is just a suggestion. In your code example, your loop does not make sense, so I d advise you to read up on loops.

I m going to pretend that you just read in from the command line arguments, if you need it to be able to accept multiple passwords you can generalize it. Here is how I would easily do it:

public class Password {
    public static void main(String[] args) {
        String thePassword = args[0];
        int passLength = thePassword.length();
        boolean hasLetters = false;
        boolean hasDigits = false;
        boolean hasSomethingElse = false;

        for (int i=0; i < passLength; i++) {
            char c = thePassword.charAt(i);
            if(Character.isLetter(c)) hasLetters = true;
            else if(Character.isDigit(c)) hasDigits = true;
            else hasSomethingElse = true;
        }

        if (hasLetters && hasDigits && !hasSomethingElse && (passLength >= 6)) {
            System.out.println("Password is correctly formatted");
        } else {
            System.out.println("Password is not correctly formatted");
        }
    }
}




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签