0

I am fairly new to java(as in started 2 days ago) and i would like to know how i could loop this program. I tried to do the do while function but it keeps saying that my variables cannot be resolved as a variable.

This is the code:

class GS1 {

    public static void main(String[]args){
        do {
            System.out.println("Enter your password");
            Scanner F_pass = new Scanner(System.in);
            String f_word= F_pass.next();
            System.out.println("Verify Password");
            Scanner Pass = new Scanner(System.in);
            String word = Pass.next();
        } while(f_word != word);
    }
}
Drew Kennedy
  • 4,118
  • 4
  • 24
  • 34
Jayden Freh
  • 99
  • 1
  • 2
  • 7
  • You're missing a close parenthesis `)` in your while condition. – azurefrog Jun 26 '15 at 17:02
  • you should also look at this: http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java – Stephen Buttolph Jun 26 '15 at 17:05
  • You do not need 2 `Scanner` objects and, obviously, do not need to recreate them on every iteration. Do not compare strings with `==` use `equals()` method. – PM 77-1 Jun 26 '15 at 17:06
  • Also, you can't use variables outside of the scope in which they are defined. Anything you declare inside a set of braces `{` `}` cannot be seen outside of them. That means `f_word` and `word`, being declared inside your do-block, cannot be seen in the while-statement. – azurefrog Jun 26 '15 at 17:06
  • Ahh that makes sense. Thank you so much. – Jayden Freh Jun 26 '15 at 17:12

1 Answers1

0

This seems like it would work. Typically you only need one instance of a Scanner object, and it will work throughout the entire class--depending on the scope that you use.

public static void main(String[] args)
 {
  // TODO Auto-generated method stub
  Scanner input = new Scanner(System.in);
  String origPass = "Original";
  String verify = "Verify";

  while(!origPass.equals(verify)){

     System.out.println("Enter your password");
     origPass = input.nextLine();

     System.out.println("Verify your password");
     verify = input.nextLine();
  }
 }

All I did was compare the values of the two string. If they are not the same, your program will repeat until the condition is satisfied. You can add a print statement to let the user know it was an incorrect password should they not have matching values. Hope this is what you were looking for.

Peter Kaminski
  • 822
  • 1
  • 12
  • 21
  • Just curious, why did you assign origPass="Original" and verify="Verify"? – Jayden Freh Jun 26 '15 at 17:35
  • Jayden, this prevents your original while loop from evaluating as true. If I set it as orig = "" and verify = "", then they would be equal and you would not enter the loop. You can make these any value you like, as long as they are not equivalent. – Peter Kaminski Jun 26 '15 at 17:37