等待字符串变得平等的正确方法

时间:2008-12-02 14:12:14

标签: java while-loop cpu-cycles

在Swing应用程序中,只有在用户输入正确答案后,方法才会继续。正确的答案存储在一个字符串中,用户答案由另一个字符串的监听器设置。所以,代码是

while (!correctAnswer.equals(currentAnswer)) {
         // wait for user to click the button with the correct answer typed into the textfield
}
// and then continue

这种方法一切都很好还是你会以某种方式重构它?它不会对CPU造成额外的惩罚吗? 这有点similar question

5 个答案:

答案 0 :(得分:6)

正如其他人所建议的那样,你需要为按钮指定一个监听器,按下按钮时会调用该按钮。

这是一个不完整的示例,说明了如何使用ActionListener并实现按下按钮时调用的actionPerformed方法:

...
final JTextField textField = new JTextField();
final JButton okButton = new JButton("OK");
okButton.addActionListner(new ActionListener() {
    public void actionPerformed(ActionEvent e)
    {
        if ("some text".equals(textField.getText()))
            System.out.println("Yes, text matches.");
        else
            System.out.println("No, text does not match.");
    }
});
...

您可能只想在按钮和文本字段所在的类中实现ActionListener,因此您无需将这两个对象声明为final。 (我只是使用匿名内部类来保持示例简短。)

有关详细信息,您可能需要查看How to Write an Action Listener中的The Java Tutorials

此外,有关事件如何在Java中工作的一般信息,“Java教程”中的Lesson: Writing Event Listeners可能很有用。

修改:将if语句中的表达式从textField.getText().equals("some text")更改为"some text".equals(textField.getText()),以阻止NullPointerException textField null根据Shiny先生和New的评论提出的建议是{{1}}。

答案 1 :(得分:5)

你是UI编程新手吗?我问的原因是你的答案是基于程序化的编码风格,而不是用户界面的。它往往是事件驱动的。

在这种情况下,解决方案非常简单:向提交按钮添加一个事件监听器(ActionListener)并在那里检查结果。如果可以,继续。如果没有,请说出来,让他们再试一次。

答案 2 :(得分:2)

我认为我没有得到那里的逻辑,但它让我想起旧的基本时代...... :-)我不明白为什么应用程序强迫用户输入已知的东西(除非是密码或某事)。

你写的是由听众观察的打字。那么为什么不在那里进行测试呢?不要做一个等待事件的循环,让Java做(和其他东西)。如有必要,请将您的逻辑分成两部分,当您在侦听器中检测到正确的输入时,转到第二部分。

我希望这有意义......; - )

答案 3 :(得分:2)

是的,正如大家在这里所说的那样。

对于gui app,处理用户输入的最佳方法是等待事件被触发。

然后可以使用一种方法来验证输入,如果成功,您可以继续使用该流,这可以转到另一页。

这是一个完整(但简单)的登录屏幕示例,用于验证用户输入以及是否成功执行某些操作。

此代码没有其他值,只显示在完整的准备运行示例中如何应用此概念。

simple gui http://img229.imageshack.us/img229/1532/simplenz0.png

// * used for brevity. Preffer single class per import
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.net.*;
import java.io.*;


public class MatchString{

    private final JTextField password;
    private final JFrame frame;

    public static void main( String [] args ){
        MatchString.show();
    }

    public static void show(){
        SwingUtilities.invokeLater( new Runnable(){
            public void run(){
                new MatchString();
            }
        });
    }

    private MatchString(){
        password = new JPasswordField( 20 );
        frame = new JFrame("Go to www.stackoverflow");
        init();
        frame.pack();
        frame.setVisible( true );
    }


    private void init(){

        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

        frame.add( new JPanel(){{
            add( new JLabel("Password:"));
            add( password );
        }});

        // This is the key of this question.
        // the password textfield is added an 
        // action listener
        // When the user press enter, the method 
        // validatePassword() is invoked.
        password.addActionListener( new ActionListener(){
            public void actionPerformed( ActionEvent e ) {
                validatePassword();
            }
        });
    }


    private void validatePassword(){            
        // If the two strings match
        // then continue with the flow
        // in this case, open SO site.    
        if ( "stackoverflow".equals(password.getText())) try {
            Desktop.getDesktop().browse( new URI("http://stackoverflow.com"));
            frame.dispose();
        } catch ( IOException ioe ){
            showError( ioe.getMessage() );
        } catch ( URISyntaxException use ){
            showError( use.getMessage() );
        } else {
            // If didn't match.. clear the text.
            password.setText("");
        }
    }
 }

答案 4 :(得分:0)

如果您的字符串来自GUI用户的人类用户,那么优化性能的重要性就很小。人类将无法每秒输入超过一到三个字符串,这对机器来说无关紧要。

在这种特殊情况下,你需要做一些事情来获得测试输入,我建议使用do-while循环。