2017-04-09 24 views
1

사용자가 JtextField에 0-9 또는 + -/* 이외의 값을 입력하면 JOptionPane 디스플레이 사용자에게 오류가 발생했습니다.
이 작업을 수행하는 데 몇 가지 다른 방법이 있습니다. 어쩌면 documentListener 또는 Inputverifyer 일 수 있습니다.사용자 입력이 숫자 (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(); 
    } 

} 
+0

이것은 달라질 수 있습니다. 실시간 유효성 검사를 위해 DocumentFilter를 사용할 수 있습니다. 유효성 확인을위한 InputVerifier/ActionListener/FocusListener – MadProgrammer

답변

0

당신은 당신의 문제를 해결하기 위해 정규식을 사용할 수 있습니다, 여기에 당신이 당신의 문제를 해결하는 데 사용할 수있는 간단한 예입니다

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+") 귀하의 의견이 숫자 다음은

+0

(str.matches ("\\ d +")) 및 (str.matches ("\\ w +")) 당신은 정교 할 수 있었다. 감사합니다 –

+0

@MikeR 내 업데이트를 지금 확인하십시오 –

+0

내 코드를 업데이트했습니다. 그러나 제대로 작동하지 않습니다 ... –

0

true를 돌려줍니다 경우, 당신은 사용자가 입력 한 표현의 유효성을 검사 String.matches()을 사용할 수 있습니다. 이것에 대한

그래서 기본 코드 :

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!"); 

을 여전히 여기에 당신은 두 개의 사업자가 지속적으로 온다 다른 요구 사항 및 기타 물건 등을 잘 확인해야합니다.