0

Below is the source for the program. However when I run the program and use a password, for example "x", it will show "x" in the list of guessed passwords but it wont realize that "x" is the correct answer. I put in a if-else loop to break the while loop when the correct password is found, but it still doesn't stop. Any advice? Thanks in advance.

import java.util.*;
import java.io.*;
class pwcracker
{
public static void main (String[] args)
{
    Scanner scan = new Scanner( System.in );
    Random rand = new Random();

  Runtime.getRuntime().availableProcessors();

  String pw, choices, guess;
    long tries;
    int j, length;

    System.out.println("Enter a password that is up to 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);

  System.out.println("for TEST- Guess: " + guess + "pw :"+pw);


  if (guess !=  pw){

  while  (guess !=  pw) 
    { 
        j = 0;
        guess = "";

        while ( j < length )
        {
            guess = guess + choices.charAt( rand.nextInt ( choices.length() ) );
            j = j + 1;

        if (guess == pw)
     {
       System.out.println("Match found, ending loop..");
       break;
     }

        }
                System.out.println("2 Guess: " + guess + " pw :"+pw);       //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.");
}
}
Prithvi Boinpally
  • 427
  • 1
  • 9
  • 23
  • 2
    Don't compare Strings using `==`. Use the `equals(...)` or the `equalsIgnoreCase(...)` method instead. Understand that `==` checks if the two *objects* are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. – Hovercraft Full Of Eels Jan 10 '15 at 17:20
  • ok, thank you!I should read up on the "equals()" operator. – Prithvi Boinpally Jan 10 '15 at 17:29

0 Answers0