【问题标题】:differentiating inputs by user in JOptionPane在 JOptionPane 中区分用户的输入
【发布时间】:2017-12-08 16:24:14
【问题描述】:

我想编写一个程序,其中向用户显示一个框并要求输入名称。

如果姓名输入正确(真实姓名),则会出现最终消息,但如果例如用户键入整数,程序会要求用户再次在字符串中键入真实姓名。

代码:

import javax.swing.*;

public class Project018 {
    public static void main(String[] args) {

    String name = JOptionPane.showInputDialog("What is your name?");

    try {

    int number = Integer.parseInt(name);

        } catch (NumberFormatException n){

             JOptionPane.showMessageDialog(null, "Dear " + name + "\nwelcome to java programming course");
        } 


    String message = String.format("your name must not contain any number");

        JOptionPane.showMessageDialog(null, message);
    }

}

我想知道当用户输入整数时如何将程序循环回顶部,以及当输入真实姓名时如何跳过第二条消息

【问题讨论】:

标签: java swing joptionpane


【解决方案1】:

我想知道当用户输入一个整数时如何将程序循环回顶部

好吧,为此我会使用do-while 循环。

为了检查输入是否 / 有数字,您不应该尝试将数字解析为整数。相反,我会使用PatternMatcherregex。否则你不会考虑这种情况:Foo123

在这种情况下,类似于:[0-9]+ 用于正则表达式,如果 Matcher 与之匹配,则它有一个数字。

输入真实姓名后如何跳过第二条消息

基于Matcher 是否匹配您显示的一个对话框或另一个

例如:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

public class LoopingJOptionPane {
    private static final String REGEX = "[0-9]+";

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new LoopingJOptionPane()::createAndShowGui);
    }

    private void createAndShowGui() {
        boolean found = true;
        do { //This repeats this code if input is incorrect
            Pattern pattern = Pattern.compile(REGEX);

            String name = JOptionPane.showInputDialog("Enter your name");
            Matcher matcher = pattern.matcher(name); //We try to find if there's a number in our string

            found = matcher.find();

            if (found) { //If there's a number, show this message
                JOptionPane.showMessageDialog(null, "Please write only letters");
            } else { //Otherwise show this one
                JOptionPane.showMessageDialog(null, "Welcome " + name);
            }
        } while (found); //If it has no numbers, don't repeat
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-26
    • 2014-01-03
    • 1970-01-01
    • 2011-03-08
    • 2016-03-17
    • 1970-01-01
    相关资源
    最近更新 更多