【问题标题】:How can i prevent users from entering characters, strings and empty space using JOptionpane如何防止用户使用 JOptionpane 输入字符、字符串和空格
【发布时间】:2017-01-20 19:13:41
【问题描述】:

如何防止用户使用JOptionPane 输入字符、字符串和空格?我已经在互联网上蹂躏了答案,但没有任何结果。请帮忙,我需要在三天内完成。 这是我的代码:

int num, ctr, ctrodd=0, ctreven=0;
for (ctr=1;ctr<=15;ctr++)
{
    num=Integer.parseInt(JOptionPane.showInputDialog("Enter number "));

    if  (!num.hasNextInt()) 
    {
        JOptionPane.showMessageDialog(null,"That's not a number!");
        ctr--;
        num.next();
    }
    else if (num%2==0)
    {
        ctreven++;
    }
    else if (num%2==1)
    {
        ctrodd++;
    }
    ctr++;
}
JOptionPane.showMessageDialog(null,"Odd"+ctrodd+"\neven"+ctreven);

【问题讨论】:

    标签: java string char int joptionpane


    【解决方案1】:

    插入:

     if  (!num.hasNextInt()) 
        {
        JOptionPane.showMessageDialog(null,"That's not a number!");
        ctr--;
        num.next();
        }
    

    试试这个:

    while (!num.hasNextInt()) 
    {
    JOptionPane.showMessageDialog(null,"That's not a number!");
    num.next();
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用 JFormattedTextField 和 MaskFormatter 调用 JOptionPane.showOptionDialog。 MaskFormatter 可以限制允许在各个位置输入的字符类型。

      https://docs.oracle.com/javase/7/docs/api/javax/swing/text/MaskFormatter.html

      描述所有字符。

      此代码允许用户输入最多但不超过 4 位数字。

      public static void main(String[] args) throws ParseException
      {
          JFormattedTextField field = new JFormattedTextField(new MaskFormatter(
                  "####"));
          field.setColumns(10);
          field.setEnabled(true);
          field.setEditable(true);
          JOptionPane.showOptionDialog(null, "Message", null, 0, 0, null,
                  new Object[]
                  { field }, field);
          System.out.println(field.getText());
      }
      

      【讨论】:

      • 很好,但我如何在 if else 语句中使用它
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-20
      • 2020-01-02
      • 2015-01-31
      • 1970-01-01
      • 1970-01-01
      • 2016-03-17
      • 1970-01-01
      相关资源
      最近更新 更多