简体   繁体   中英

How can I throw an error if a string contains any element other than int or +-/* and prevent program from further execution?

How can I throw an error if a string contains any element other than int or +-/* and prevent program from further execution?

public ExpressionTree(String s) {
      
        
            else return;
        }
        root = stack.pop();
   }

You'll want to throw an exception . This isn't recommended though, because it will cause your entire application to terminate unless you catch the exception. The better solution would be to try and recover from the bad input.

However, if you do want to throw an exception, a ParseException would be appropriate because you're trying to read a string. You can throw it like this: throw new ParseException("Illegal characters found") . If you don't want to handle the exception in the method and instead want to do it later, you can throw the exception "up" the call stack by declaring the exception you throw in the method, like this:

public ExpressionTree(String s) throws ParseException {}

You can change your code with the below-mentioned code which will throw a Runtime/Custom exception on not matched with one of int or operator:

public ExpressionTree(String s) {

        MyStack<ExpressionNode> stack = new MyStack<ExpressionNode>();
        String[] expression = s.split(" ");
        boolean isOperator;

        for (int i = 0; i < expression.length; i++) {
            String x = expression[i];
            if(!x.matches("(^\\d+\\d$)|(^[+\\-*/]$)")){
                throw new RuntimeException();//Custom Exception can be replaces with Runtime Exception with appropriate message 
            }else {
                if (x.matches("[0-9]+")) {
                    ExpressionNode d = new ExpressionNode(Integer.parseInt(x));
                    stack.push(d);
                } else if (x.equals("+") || x.equals("-") || x.equals("*") || x.equals("/")) {
                    isOperator = true;
                    ExpressionNode t = new ExpressionNode(x.charAt(0));
                    t.right = stack.pop();
                    t.left = stack.pop();
                    stack.push(t);
                }
            }
        }
        root = stack.pop();
    }

Please check this.

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

private boolean  checkBadMessage(String ipMessage)
    {
        Pattern pattern = Pattern.compile("([0-9+-/*])+");
        Matcher matcher = pattern.matcher(ipMessage);
        int len = 0;
        while (matcher.find())
        {
            len = len + matcher.group().length();
        }
        if (len != ipMessage.length())
        {
            return true;
        }

        return false;
    }
    
    
 public ExpressionTree(String s) {

        MyStack<ExpressionNode> stack = new MyStack<ExpressionNode>();
        String[] expression = s.split(" ");
        boolean isOperator;

        for (int i = 0; i < expression.length; i++) {
            String x = expression[i];
            if(checkBadMessage(x)){
                throw new RuntimeException();
            }else {
                if (x.matches("[0-9]+")) {
                    ExpressionNode d = new ExpressionNode(Integer.parseInt(x));
                    stack.push(d);
                } else if (x.equals("+") || x.equals("-") || x.equals("*") || x.equals("/")) {
                    isOperator = true;
                    ExpressionNode t = new ExpressionNode(x.charAt(0));
                    t.right = stack.pop();
                    t.left = stack.pop();
                    stack.push(t);
                }
            }
        }
        root = stack.pop();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM