简体   繁体   中英

Java Scanner stop reading input if receives bad character

I'm working on a Reverse Polish Notation program, and I'm having issues with dealing with an invalid expression... I can deal with it if it has too few operators or operands, but I can't deal with having any characters that aren't "(", "+", "-", "*", and "#".

Basically I want to know of a way to skip the rest of the line (or force a pound symbol into the input) instead of reading the whole expression.

Here's my code below:

public class RpnEvaluator
{
   private Scanner stdin;
   private Stack stack = new Stack(50);
   private Queue queue = new Queue(50);
   private String expression = "";
   private String interValue = "";
   private int numExpressions = 0;

   /**
   Runs the RPN Evaluator.
   */
   public void run()
   {  
      stdin = new Scanner(System.in);
      while( stdin.hasNext() )
      {
         String input = stdin.next();
         if( input.charAt(0) == '(' )
            addOperand(input);
         else if( input.equals("+") || input.equals("-") || input.equals("*") )
            performOperation(input.charAt(0));
         else if( input.equals("#") )
            outputExpression();
         else
            invalidExpression(); **// Here is where I need to deal with anything that isn't above and output anything BEFORE the bad value, AND the value itself.**

      }
      System.out.println("Normal Termination of Program 3.");
   }

For example: An input such as

(2/9) B (4/3) / # 

should return this output:

Expression 1 is: (2/9)B
Invalid Expression
Intermediate results:

After looking over the notes, I found a section where we first introduced Reverse Polish Notation and we actually talked about dealing with possible errors, from those notes, I created these two methods that seem to do the trick perfectly.

private void skipExpression()
{
   while( stdin.hasNext() )
    {
      input = stdin.next();
      if( input.equals("#") )
         break;
   }
}

private void invalidExpression()
{
   skipExpression();
   numExpressions++;
   System.out.println("Expression " + numExpressions + " is: " + expression);
   System.out.println("Invalid Expression");
   System.out.println("Intermediate results: " + interValue);
   expression = "";
   interValue = "";
   stack.clear();
   queue.clear();
}

I would first test with hasNext(Pattern pattern) if the following token is valid with a pattern like [0-9+/*\\-#] or one more context-specific, and if not I would skip(Pattern pattern) with a pattern matching every character but carriage return, which . does

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