Hello all, I'm new to java and new to forum. It's great to see all the activity here and active posts. Now on to business.
I'm teaching myself programming using an online cs tutorial. I can work through most of the programming, but occasionally I get stuck and I can't find the bug.
Here is a program I'm trying to write:
Write a program that asks the user for a password. The user enters a password (which must be short). Now pretend that this password is a secret from the rest of the program, which must try to guess it. The program then uses the password generator repeatedly until a randomly generated password matches the password the user entered. Assume that the user's password is five characters or less (otherwise this program will never end). Write out the number attempts it took to find the password. Here are some example runs:
K:\cai\>java PasswordCracker
Enter a "secret" password-->ant
Here is your password: ant
It took 2181892 tries to guess it
I've learned up to if, else, while loops, and random.
Here is the code I've written:
import java.util.*; import java.io.*; class pwcracker { public static void main (String[] args) { Scanner scan = new Scanner( System.in ); Random rand = new Random(); String pw, choices, guess; long tries; int j, length; System.out.println("Enter a password that is less than 5 chars and contains no numbers: "); pw = "" + scan.nextLine(); length = pw.length(); choices = "abcdefghijklmnopqrstuvwxyz"; tries = 0; guess = ""; System.out.println("Your pw is: " + pw); System.out.println("The length of your pw is: " + length); while ( guess != pw ) { j = 0; guess = ""; while ( j < length ) { guess = guess + choices.charAt( rand.nextInt ( choices.length() ) ); j = j + 1; } System.out.println("Guess: " + guess); //this is for me to view the actual guesses tries = tries + 1; } System.out.println("Here is your password: " + guess); System.out.println("It took " + tries + " tries to guess it."); } }
I've run my program many times, but no matter what I do, the program ceases to see that at some point "guess == pw". What I mean is that I've tried just typing in one letter, say the letter "a". The inner while loop guesses the string "a", but it skips past it as if nothing has happened.
Edit: My program just continues forever, it fails to recognize when the while loop ends.