【问题标题】:Strange behaviour of a while-loop [duplicate]while循环的奇怪行为[重复]
【发布时间】:2014-12-14 11:33:16
【问题描述】:

我目前正在测试各种获取用户输入的方法。今天我正在使用 OnClosing() 进行测试,这似乎有效。我的问题是,如果我没有在 while() - 循环中放入任何东西,它就不起作用。用代码更容易展示:

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

好的。这就是我获取字符串的方式。

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());
}
}

除非我在 while() 循环中随机放置一些东西,否则这不起作用。让我告诉你。这样工作

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

为什么它不能使用空循环?

【问题讨论】:

    标签: java oop while-loop passwords


    【解决方案1】:

    经过大量搜索,我找到了答案。 发生这种情况是因为循环下方的代码“无法访问”,因为循环不循环任何内容(仅使用处理器容量)。

    我的循环可以用同样的方式来说明:

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

    这是一种可怕的循环方式,但如果你绝对需要循环。确保循环确实做某事

    这仍然是一种可怕的做法,但我会举一个例子:

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

    现在循环实际上做了一些事情,但不推荐。我会用另一种方法来解决这个问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多