Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/392.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如果用户输入的不是数字(0-9)或算术运算符(+;-*/),如何使JOptionPane显示错误_Java_User Input_Jtextfield_Verify - Fatal编程技术网

Java 如果用户输入的不是数字(0-9)或算术运算符(+;-*/),如何使JOptionPane显示错误

Java 如果用户输入的不是数字(0-9)或算术运算符(+;-*/),如何使JOptionPane显示错误,java,user-input,jtextfield,verify,Java,User Input,Jtextfield,Verify,如果用户在JText字段中输入除0-9或+-/*以外的任何内容,则JOptionPane会向用户显示错误。 我看到了一些不同的方法来做这件事。。。 可能是文档监听器或输入验证器 主类 package p2gui; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; import java.awt.event.*; impo

如果用户在JText字段中输入除0-9或+-/*以外的任何内容,则JOptionPane会向用户显示错误。
我看到了一些不同的方法来做这件事。。。 可能是文档监听器或输入验证器

主类

package p2gui;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.event.*;
import javax.swing.JOptionPane;

/**
 *
 *
 */
public class P2GUI extends JFrame implements ActionListener {

    JFrame f = new JFrame("Three Address Generator");// Title

    private final JButton evaluate;
    private final JLabel textfieldLabel;
    private final JTextField entryField;
    private final JLabel resutfieldlabel;
    private final JTextField resultField;
    private final JOptionPane popup = new JOptionPane();

    public void display() {
        setVisible(true);
    }

    P2GUI() {

        f.setSize(425, 180);//450 width and 525 height  
        f.setLayout(null);//using no layout managers  
        f.setVisible(true);//making the frame visible  //window size
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        textfieldLabel = new JLabel("Enter Postfix Expression");
        f.add(textfieldLabel);
        textfieldLabel.setBounds(10, 10, 160, 25);

        entryField = new JTextField("");
        entryField.addActionListener(this);//ActionListener
        f.add(entryField);
        entryField.setBounds(160, 10, 220, 25);

        evaluate = new JButton("Construct Tree");//creating instance of JButton  
        evaluate.addActionListener(this);//ActionListener
        f.add(evaluate);
        evaluate.setBounds(137, 55, 130, 30);

        resutfieldlabel = new JLabel(" Infix Expression ");
        f.add(resutfieldlabel);
        resutfieldlabel.setBounds(20, 100, 100, 25);

        resultField = new JTextField("");
        resultField.addActionListener(this);//ActionListener
        resultField.setEditable(false);
        f.add(resultField);

        resultField.setBounds(125, 100, 220, 25);

    }

   @Override
   public void actionPerformed(ActionEvent e) {


    if (e.getSource() == evaluate) {
        String fullString = entryField.getText().trim();
        if (fullString.matches("\\d+") || fullString.matches("[-+*/]")) {
            Convert conversion = new Convert();
            resultField.setText(conversion.convert(fullString));
            eraseTextField();
        }else {
            JOptionPane.showMessageDialog(null,"Wrong input enter a digit or 
    arithmetic operator");
            eraseTextField();
        }

    }

}
    public void eraseTextField() {
        entryField.setText("");
        entryField.requestFocus();
    }

    public static void main(String[] args) {
        P2GUI p1GUI;
        p1GUI = new P2GUI();

    }
}
package p2gui;

import java.util.Stack;

/**
 *
 * @author Mike
 */
public class Convert {

    /**
     * Checks if the input is operator or not
     *
     * @param c input to be checked
     * @return true if operator
     */
    private boolean operator(char c) {
        return c == '+' || c == '-' || c == '*' || c == '/' || c == '^';
    }

    /**
     * Converts any postfix to infix
     *
     * @param postfix String expression to be converted
     * @return String infix expression produced
     */
    public String convert(String postfix) {
        Stack<String> s = new Stack<>();

        for (int i = 0; i < postfix.length(); i++) {
            char c = postfix.charAt(i);
            if (operator(c)) {
                String b = s.pop();
                String a = s.pop();
                s.push("(" + a + c + b + ")");
            } else {
                s.push("" + c);
            }
        }

        return s.pop();
    }

}
转换。java类

package p2gui;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.event.*;
import javax.swing.JOptionPane;

/**
 *
 *
 */
public class P2GUI extends JFrame implements ActionListener {

    JFrame f = new JFrame("Three Address Generator");// Title

    private final JButton evaluate;
    private final JLabel textfieldLabel;
    private final JTextField entryField;
    private final JLabel resutfieldlabel;
    private final JTextField resultField;
    private final JOptionPane popup = new JOptionPane();

    public void display() {
        setVisible(true);
    }

    P2GUI() {

        f.setSize(425, 180);//450 width and 525 height  
        f.setLayout(null);//using no layout managers  
        f.setVisible(true);//making the frame visible  //window size
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        textfieldLabel = new JLabel("Enter Postfix Expression");
        f.add(textfieldLabel);
        textfieldLabel.setBounds(10, 10, 160, 25);

        entryField = new JTextField("");
        entryField.addActionListener(this);//ActionListener
        f.add(entryField);
        entryField.setBounds(160, 10, 220, 25);

        evaluate = new JButton("Construct Tree");//creating instance of JButton  
        evaluate.addActionListener(this);//ActionListener
        f.add(evaluate);
        evaluate.setBounds(137, 55, 130, 30);

        resutfieldlabel = new JLabel(" Infix Expression ");
        f.add(resutfieldlabel);
        resutfieldlabel.setBounds(20, 100, 100, 25);

        resultField = new JTextField("");
        resultField.addActionListener(this);//ActionListener
        resultField.setEditable(false);
        f.add(resultField);

        resultField.setBounds(125, 100, 220, 25);

    }

   @Override
   public void actionPerformed(ActionEvent e) {


    if (e.getSource() == evaluate) {
        String fullString = entryField.getText().trim();
        if (fullString.matches("\\d+") || fullString.matches("[-+*/]")) {
            Convert conversion = new Convert();
            resultField.setText(conversion.convert(fullString));
            eraseTextField();
        }else {
            JOptionPane.showMessageDialog(null,"Wrong input enter a digit or 
    arithmetic operator");
            eraseTextField();
        }

    }

}
    public void eraseTextField() {
        entryField.setText("");
        entryField.requestFocus();
    }

    public static void main(String[] args) {
        P2GUI p1GUI;
        p1GUI = new P2GUI();

    }
}
package p2gui;

import java.util.Stack;

/**
 *
 * @author Mike
 */
public class Convert {

    /**
     * Checks if the input is operator or not
     *
     * @param c input to be checked
     * @return true if operator
     */
    private boolean operator(char c) {
        return c == '+' || c == '-' || c == '*' || c == '/' || c == '^';
    }

    /**
     * Converts any postfix to infix
     *
     * @param postfix String expression to be converted
     * @return String infix expression produced
     */
    public String convert(String postfix) {
        Stack<String> s = new Stack<>();

        for (int i = 0; i < postfix.length(); i++) {
            char c = postfix.charAt(i);
            if (operator(c)) {
                String b = s.pop();
                String a = s.pop();
                s.push("(" + a + c + b + ")");
            } else {
                s.push("" + c);
            }
        }

        return s.pop();
    }

}
包p2gui;
导入java.util.Stack;
/**
*
*@作者迈克
*/
公共类转换{
/**
*检查输入是否为运算符
*
*@param c要检查的输入
*@return true if运算符
*/
专用布尔运算符(字符c){
返回c='+'| | c='-'| | c='*'| | c='/'| | c='^';
}
/**
*将任何后缀转换为中缀
*
*要转换的@param后缀字符串表达式
*@返回字符串中缀表达式已生成
*/
公共字符串转换(字符串后缀){
堆栈s=新堆栈();
for(int i=0;i
您可以使用正则表达式来解决问题,下面是一个简单的示例,您可以使用它来解决问题:

String str = "123";
if (str.matches("\\d+")) {
    JOptionPane.showMessageDialog(null, "Degit");
} else if (str.matches("[-+*/]")) {
    JOptionPane.showMessageDialog(null, "arithmetic operator( + - * /)");
}else{
    JOptionPane.showMessageDialog(null, "Incorrect input");
}
解释

str.matches(“[-+*/]”
如果您的输入是-+*或/,那么它将返回true。

str.matches(“\\d+”)
如果您的输入是一个数字,那么它将返回true

您可以使用正则表达式来解决问题,下面是一个简单的示例,您可以使用它来解决问题:

String str = "123";
if (str.matches("\\d+")) {
    JOptionPane.showMessageDialog(null, "Degit");
} else if (str.matches("[-+*/]")) {
    JOptionPane.showMessageDialog(null, "arithmetic operator( + - * /)");
}else{
    JOptionPane.showMessageDialog(null, "Incorrect input");
}
解释

str.matches(“[-+*/]”
如果您的输入是-+*或/,那么它将返回true。
str.matches(“\\d+”)
如果您的输入是一个数字,那么它将返回true

您可以用来验证用户输入的表达式

因此,基本代码如下:

String expression = "9+45-3/5*9"; //store expression here from text-field.

boolean isvalid = expression.matches("[0-9-+*/]+");

if(isvalid)
    JOptionPane.showMessageDialog(null,"Valid Expression!");
else
    JOptionPane.showMessageDialog(null,"Not Valid Expression!");
在这里,您还需要检查没有两个运算符连续出现的其他要求以及其他内容。

您可以使用来验证用户输入的表达式

因此,基本代码如下:

String expression = "9+45-3/5*9"; //store expression here from text-field.

boolean isvalid = expression.matches("[0-9-+*/]+");

if(isvalid)
    JOptionPane.showMessageDialog(null,"Valid Expression!");
else
    JOptionPane.showMessageDialog(null,"Not Valid Expression!");

在这里,您还需要检查没有两个操作员连续出现的其他要求以及其他内容。

这取决于具体情况。可以使用DocumentFilter进行实时验证,使用InputVerifier/ActionListener/FocusListener进行后期验证。您可以使用DocumentFilter进行实时验证,使用InputVerifier/ActionListener/FocusListener进行后期验证我对(str.matches(\\d+))和(str.matches(\\w+))有点困惑,请详细说明。Thanksif(fullString.matches(\\d+)| | fullString.matches([-+*/]){这是为多个条件设置的合适方法吗?但是你可以设置多个条件@MikeRI,我有点混淆了(str.matches(\\d+))和(str.matches(\\w+)。你能详细说明一下吗?Thanksif(fullString.matches(\\d+)| fullString.matches(\\d+)| fullString.matches([-+*/])){设置多个条件合适吗?{但是你可以设置多个条件@MikeR