等待字符串相等的正确方法

发布于 2024-07-09 02:26:16 字数 512 浏览 9 评论 0原文

在 Swing 应用程序中,只有在用户输入正确答案后,方法才应继续。 正确答案存储在 String 中,用户答案由侦听器设置为另一个 String。 那么,代码是

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

这种方法一切都好吗,还是您会以某种方式重构它? 这不会对CPU造成额外的惩罚吗? 这是一个有点 类似的问题

In a Swing app a method should continue only after user enters a correct answer. The correct answer is stored in a String with user answer being set by a listener to another String. So, the code is

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

Is everything fine with this approach or would you somehow refactor it? Doesn't it impose extra penalty on CPU?
Here's a somewhat similar question.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

骄傲 2024-07-16 02:26:16

正如其他人所建议的,您需要为按钮分配一个侦听器,按下按钮时将调用该侦听器。

这是一个不完整的示例,说明如何使用 < code>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。 (我只是使用了一个匿名内部类来保持示例简短。)

有关更多信息,您可能需要查看 如何编写操作侦听器 来自 Java 教程

另外,有关 Java 中事件如何工作的一般信息,请参阅课程:《Java 教程》中的编写事件侦听器 可能会很有用。

编辑:if 语句中的表达式从 textField.getText().equals("some text") 更改为 "some text根据 Mr 的建议,“.equals(textField.getText()) 是为了防止 textFieldnull 时出现 NullPointerException闪亮和纽的评论。

As others have suggested, you'll want to use assign a listener to the button, which will be called when the button is pressed.

Here's a incomplete example illustrating how to use an ActionListener and implementing its actionPerformed method which is called when the button is pressed:

...
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.");
    }
});
...

You may just want to implement ActionListener in the class where the button and text field resides, so you don't need to declare the two objects as final. (I just used an anonymous inner class to keep the example short.)

For more information, you may want to take a look at How to Write an Action Listener from The Java Tutorials.

Also, for general information on how events work in Java, the Lesson: Writing Event Listeners from The Java Tutorials may be useful.

Edit: Changed the expression inside if statement from textField.getText().equals("some text") to "some text".equals(textField.getText()) in order to prevent a NullPointerException if textField was null, per suggestion from Mr. Shiny and New's comment.

陌上青苔 2024-07-16 02:26:16

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

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

Are you new to UI programming? The reason I ask is that your answer is predicated on a procedural style of coding, which isn't what UIs are about. It tends to be event-driven.

In this case the solution is pretty easy: add an event listener (ActionListener) to the submit button and check the result there. If its OK, go on. If not, say so and let them try again.

红衣飘飘貌似仙 2024-07-16 02:26:16

我不认为我明白其中的逻辑,但它让我想起了旧的 Basic 时代...:-) 我不明白为什么应用程序会强制用户输入已知的内容(除非它是密码或其他内容) 。

您编写的打字内容会被侦听器观察到。 那么为什么不在那里进行测试呢? 不要循环等待事件,让 Java 来做(以及其他事情)。 如有必要,将您的逻辑分成两部分,并在检测到侦听器中给出了正确的输入时转到第二部分。

我希望这是有道理的... ;-)

I don't think I get the logic there, but it reminds me of old Basic times... :-) I don't see why the application forces the user to type something already known (unless it is a password or something).

You write the typing is observed by a listener. So why not do the test there? Don't do a loop waiting for an event, let Java do it (and other stuff). If necessary, break your logic in two, and go to the second part when you detect the correct input is given in the listener.

I hope this makes sense... ;-)

一个人的夜不怕黑 2024-07-16 02:26:16

是的,就像这里每个人都说的那样。

对于 GUI 应用程序来说,处理用户输入的最佳方法是等待事件被触发。

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

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

除了在完整的准备运行示例中展示如何应用此概念之外,此代码没有其他价值。

简单的图形用户界面 http://img229.imageshack.us/img229/1532/simplenz0.png< /a>

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

Yes, as everyone said here.

For a gui app the best way to handle user input is to wait for an event to be fired.

Then a method could be used to validate the input and if succeed you can continue with the flow, that could be go to another page.

Here's a complete ( yet simple ) example of a login screen, that validates the user input and if succeed performs some action.

This code has no other value than show in a complete ready to run sample how this concept is applied.

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("");
        }
    }
 }
梦里南柯 2024-07-16 02:26:16

如果您的字符串以 GUI 速率来自人类用户,那么优化性能就没有什么意义。 人类每秒只能输入一到三个字符串,这对机器来说根本不算什么。

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

If your strings are coming from a human user at GUI rates, there's very little point in optimizing for performance. The human won't be able to enter more than perhaps one to three strings per second, and that's nothing for the machine.

In this particular case, where you need to do stuff to get an input to test, I would suggest using a do-while loop.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文