0

I am currently testing various ways of getting user-input. Today I was testing with the OnClosing(), which seem to work. My problem is that if I don't put anything in the while() - loop, it doesn't work. Its easier to show with code:

public MyClass() {
    String myPassword= new Password().getpw();
}

ok. This is how I'm getting the string.

public class Password {

private boolean goon                = true;
private JPasswordField jpassword    = new JPasswordField ();

public Password() {
  JFrame f = new JFrame("Type your password here, get it by closing the frame");
  f.getContentPane().add(jpassword);
  f.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        goon = false;
      }
      }
     );
  f.setSize(400,65);
  f.show();
}

public String getpw() {
    while (goon);
    return new String(jpassword.getPassword());
}
}

This doesn't work unless I put something random in the while()-loop.. let me show you. This way it works

public String getpw() {
    while (goon) {
      System.out.println(""); 
    }
    return new String(jpassword.getPassword());
}

Why is it not working with an empty loop?

Mr.Turtle
  • 2,950
  • 6
  • 28
  • 46

1 Answers1

0

I found the answer after a lot of searching. This happens because the code beneth the loop is "unreachable", because the loop loops nothing (only uses processor-capasity).

My loop can be illustrated the same way like this:

public String getpw() {
    while (goon) {
      doNothing();
    }
    return new String(jpassword.getPassword());
}

private void doNothing() { }

This is a horrible way of doing a loop, but if you absolutely need to do the loop. Make sure the loop actually does something.

This is still a horrible way of doing it, but I'll make an example:

public String getpw() {
    String s = "";
    while (goon) {
      s += "";
    }
    return new String(jpassword.getPassword());
}

Now the loop actually does something, but its not recommended. I would use another aproach to this

Mr.Turtle
  • 2,950
  • 6
  • 28
  • 46