Input can only be string

≡放荡痞女 提交于 2020-01-07 02:44:05

问题


I'm making a JOptionpane where the user can has to enter hes name. So it can't be empty and it can't be a number

The empty part is working but now I have to find a solution for the number part

As you can see in my code I made a while loop to check if "naam" isn't empty. Now I need to find a way to check if "naam" isn't a number.

String naam = JOptionPane.showInputDialog("Geef uw naam in: ");

while (naam.equals("")) {
   JOptionPane.showMessageDialog(null, "Geef een naam in", "Geef naam", JOptionPane.ERROR_MESSAGE);
   naam = JOptionPane.showInputDialog("Geef uw naam in: ");

回答1:


You can use regex to check if it contains any digits. The regex "\\D" in java stands for a non-digit, and "+" stands for 1 or more. So you can change your while loop to:

while (!naam.matches("\\D+"))

This will include the empty equals check, as you need to have at least one non-digit for it to match.




回答2:


You could simply filter the input directly at the dialog, instead of messing about having to display error dialogs and re-showing the dialog...

import java.awt.EventQueue;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;

public class TestOptionPane08 {

    public static void main(String[] args) {
        new TestOptionPane08();
    }

    public TestOptionPane08() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JTextField name = new JTextField(10);
                ((AbstractDocument) name.getDocument()).setDocumentFilter(new DocumentFilter() {
                    public String filter(String text) {
                        StringBuilder sb = new StringBuilder(text.length());
                        for (char c : text.toCharArray()) {
                            if (!Character.isDigit(c)) {
                                sb.append(c);
                            }
                        }
                        return sb.toString();
                    }

                    @Override
                    public void insertString(DocumentFilter.FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
                        super.insertString(fb, offset, filter(string), attr);
                    }

                    @Override
                    public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
                        String filter = filter(text);
                        super.replace(fb, offset, length, filter, attrs);
                    }
                });

                JOptionPane.showMessageDialog(null, name, "Name Please", JOptionPane.QUESTION_MESSAGE);

            }
        });
    }
}

Now, you could add the JTextField to JPanel and add a JLabel as well and even error messages...




回答3:


Use regular expressions.

 if (naam.matches("\\d+")) {/*it is a number*/}

String.matches(regexp) returns true if the string matches the regular expression given as parameter. In this example, \\d+ matches one or more digits.

You may try other patterns in order to disallow strings with invalid characters (such as "My#name") but that depends on your definition of "name character".

For instance [A-Z][a-z]*(?:\\s[A-Z][a-z]*) matches strings with one or more sequences of an uppercase character followed by zero-or-more lowercase characters, each sequence separated by a single space, such as My Name Is X.



来源:https://stackoverflow.com/questions/15284062/input-can-only-be-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!