Java问题与readIn()读取我的下一个元素以及特定字符

时间:2014-03-06 23:49:59

标签: java string java.util.scanner

如何添加空格 AFTER 找到字符串中的特定字符?示例....我想在该字符串中的“#”字符后面添加一个空格。我也想知道如果我的字符串中有多个“#”,我怎么能得到我当前所处的位置。

(2/9) B (4/3) / #
(1/2) (-1/3) (3/2) (-1/11) * * - #
(1/2) + (2/2) #

有了同样的概念。我有一个看起来像这样的循环。我还更新字符串看起来像我的问题。现在我的问题是,一旦我的循环处理并获取每个元素,如果它是一个错误的输入ex。(B,/,基本上非操作数和'+'' - ''*')所以我的throwLine()跳过行中的所有内容直到#然后继续...但是在第一个#之后我的readIn似乎跳过第一个(1/2)并读入(-1/3)。如果你能回答这个问题我会很多感激。

CODE

   import java.util.Scanner;

public class RpnEvaluator
{
   private final int MAX_TOKEN = 100; 
   private Scanner stdin = new Scanner(System.in);
   private Queue myQueue = new Queue(MAX_TOKEN);
   private Stack myStack = new Stack(MAX_TOKEN);

   public void run() throws java.io.IOException
   {
      int count = 1;
      Fraction myInterMid;
      while(stdin.hasNext())
      {
         runOnce(count++);
         System.out.print("Intermediate results: ");
         while(!myQueue.isEmpty())
         {
            myInterMid = (Fraction)myQueue.remove();
            System.out.print(myInterMid.toString());
         }
         System.out.println();
         clear(myStack, myQueue);
      }
      System.out.println("Normal Termination of Program 3.");
   }

   private boolean isOperator(String input)
   {
      String[] oprtr = {"+", "-", "*"};
      for(String choice: oprtr)
         if(choice.equals(input))
            return true;
      return false;
   }

   private boolean isOperand(String input)
   {
      if(input.charAt(0) == '(')
         return true;
      return false;
   }

   private Fraction runOperation(String choice, Fraction op2, Fraction op1)
   {
      Fraction newFract = new Fraction();
      switch (choice)
      {
         case "*":
            newFract = new Fraction(op1.times(op2));
            break;
         case "+":
            newFract = new Fraction(op1.plus(op2));
            break;
         case "-":
            newFract = new Fraction(op1.minus(op2));
            break;
      }
      return newFract;
   }

   private void runOnce(int count)
   {
      String readIn = "";
      boolean valid = true;
      Fraction op1 = null;
      Fraction op2 = null;
      Fraction answer = null;
      Fraction myFract = null;
      clear(myStack, myQueue);

      doTypeCheck(readIn, myFract, valid, op1, op2, answer, count ); 
   }

   private void clear(Stack myStack, Queue myQueue)
   {
     myStack.clear();
     myQueue.clear();
   }

   private void runTheOperator(boolean valid, Fraction op2, Fraction op1,
         String readIn)
   {
       if(myStack.isEmpty())  
          valid = false;
       else
          op2 = (Fraction)myStack.pop();

       if(myStack.isEmpty())
          valid = false;
       else
       {
          op1 = (Fraction)myStack.pop();
          Fraction interMed = runOperation(readIn, op2, op1);
          myStack.push(interMed);
          myQueue.add(interMed);
       }
   }

   private void doTypeCheck(String readIn, Fraction myFract, boolean valid, 
         Fraction op1, Fraction op2, Fraction answer, int count)
   {
      Fraction stringFract;
      readIn = stdin.next();
      System.out.print("Expression " + count++ + " is: ");
      while(!readIn.equals("#") && valid == true)
      {
         if(!isOperator(readIn) && isOperand(readIn))
         {
            stringFract = new Fraction(readIn);
            System.out.print(stringFract.toString());
            myFract = new Fraction(readIn);
            myStack.push(myFract);
         }
         else if(isOperator(readIn))
         {
            System.out.print(readIn);
            runTheOperator(valid, op2, op1, readIn);
         }
         else
         {
            throwLine(readIn);
            System.out.print(readIn);
            valid = false;
         }
         readIn = stdin.next();
      }
      System.out.println();
      if(myStack.isEmpty())
         valid = false;
      else
         answer = (Fraction)myStack.pop();

      if(!myStack.isEmpty())
         valid = false;

      checkMessageValid(valid, answer);
   }

   private void checkMessageValid(boolean valid, Fraction answer)
   {
      if(valid == false)
         System.out.println("Invalid Expression");
      else
         System.out.println("The value is: " + answer.toString());
   }

   private void throwLine(String line)
   {
      while(!line.equals("#"))
      {
         line = stdin.next();
      }
   }
}

FRACTION

import java.util.StringTokenizer;

/**
Fraction class handles the individual creation of a Fraction by the 
Constructors listed. This class also handles the manipulation of individual
Fractions with the times, plus, and minus methods.
@author Adam Bloedel
*/
public class Fraction
{
   private int numerator, denominator;

   /**
   Default constructor that sets the numerator equal to one and the 
   denominator equal to 1 so that division by zero does not occur.
   */
   public Fraction()
   {
      numerator = 0;
      denominator = 1;
   }

   /**
   Copy constructor that copies the values of copyFract to the new object,
   Fraction.
   @param copyFract : The object(Fraction) that will be copied into the new
   object.
   */
   public Fraction(Fraction copyFract)
   {
      numerator = copyFract.numerator;
      denominator = copyFract.denominator;
   }

   /**
   Constructor that creates a Fraction object with specific numerator and 
   denominator numbers. If the denominator is 0, make the denominator 1. Else
   the fraction is created with the given numbers;
   @param num is the numerator for the new Fraction object
   @param denom is the denominator for the new Fraction object
   */
   public Fraction(int num, int denom)
   {
      if(denom == 0)
         denom = 1;
      else
      {
         numerator = num;
         denominator = denom;
         reduce();
      }
   }

   /**
   Another constructor that takes on a string and sorts through the string
   until the '/' is found and splits the two tokens to be the numerator and 
   denominator.
   @param fractString is the string of the fraction that will be parsed to be
   the Fraction stored
   */
   public Fraction(String fractString)
   {
      StringTokenizer str = new StringTokenizer(fractString, "(/)");
      numerator = Integer.parseInt(str.nextToken());
      denominator = Integer.parseInt(str.nextToken());
      reduce();
   }

   /**
   This method returns a string of the format: numerator/denominator as a 
   fraction would appear in Mathematics.
   @return the string that concatenates numerator/denominator together
   */
   @Override
   public String toString()
   {
      return "(" + numerator + "/" + denominator + ")";
   }

   /**
   This method checks for equality between a Fraction and an object that is 
   being checked in the parameter. If fract2 is an instance of Fraction,
   it checks if the numerator and denominator are equal to the numerator and 
   denominator of fract2.
   @param fract2 the object that is being checked for equality.
   @return true if fract2 is an instance of Fraction and if the numerator and
   denominator of the activated Fraction are equal to the numerator and
   denominator of fract2, which is being referred to by fract1.
   */
   public boolean equals(Object fract2)
   {
      if(fract2 instanceof Fraction)
      {
         Fraction fract1 = (Fraction)fract2;
         return numerator == fract1.numerator && 
                denominator == fract1.denominator;
      }
      return false;
   }

   /**
   Tests the Fraction that is multiplied or added together or even created
   via the constructors and reduces them to the most simplified form. Loops 
   through the lowest number to check if it is zero, if not then there is 
   more simplifying to do.
   */
   private void reduce()
   {
      int lowest, highest, temp;

      if(Math.abs(numerator) > Math.abs(denominator))
      {
         lowest = Math.abs(denominator);
         highest = Math.abs(numerator);
      }
      else
      {
         lowest = Math.abs(numerator);
         highest = Math.abs(denominator);
      }

      while(lowest != 0) // Loop to check if there is still more simplifying
      {
         temp = lowest;
         lowest = highest % lowest;
         highest = temp;
      }
      numerator /= highest;
      denominator /= highest;
      if(denominator < 0) // Makes denominator positive
      {
         numerator *= -1;
         denominator *= -1;
      }
   }

   /**
   Adds two Fractions together and then reduces the resulting fraction. That
   fraction is then returned as a new Fraction.
   @param z is the second Fraction that is added onto the first Fraction.
   @return newFract : this is the Fraction that is the resulting Fraction 
   from the addition of the first fraction with the fraction in the parameter.
   */
   public Fraction plus(Fraction z)
   {
      int myNumer = (numerator * z.denominator) + (z.numerator * denominator);
      int myDenom = denominator * z.denominator;

      Fraction newFract = new Fraction("(" + myNumer + "/" + myDenom + ")");
      newFract.reduce();

      return newFract;
   }

   /**
   Subtracts the Fraction in the parameters from the first Fraction. The 
   resulting fraction is reduced if possible and then returned as a new 
   Fraction.
   @param z is the second Fraction that is subtracted from the first fraction.
   @return newFract  : this is the Fraction that is the resulting Fraction 
   from the subtraction of the second Fraction from the first Fraction.
   */
   public Fraction minus(Fraction z)
   {
      int myNumer = (numerator * z.denominator) -
            (z.numerator * denominator);
      int myDenom = denominator * z.denominator;

      Fraction newFract = new Fraction("(" + myNumer + "/" + myDenom + ")");
      newFract.reduce();

      return newFract;
   }

   /**
   Multiplies the first fraction and the fraction in the parameters together.
   The resulting Fraction is then reduced and returned as a new Fraction.
   @param z is the Fraction in the parameter that is multiplied by the first
   Fraction.
   @return newFract : this is the Fraction that is the resulting Fraction from
   the multiplication of the first Fraction and the second Fraction.
   */
   public Fraction times(Fraction z)
   {
      int myNumer = this.numerator * z.numerator;
      int myDenom = this.denominator * z.denominator;

      Fraction newFract = new Fraction("(" + myNumer + "/" + myDenom + ")");
      newFract.reduce();

      return newFract;
   }

堆叠和主要(请注意,您不需要队列执行任何操作:只需忽略队列)

/**
Keeps track of a Stack of Objects and allows for a user to create a stack,
check if the stack is empty or full, add an object to the top of the stack, 
and remove the object on top of the stack. Also allows user to clear out the
stack.
@author Adam Bloedel
*/
public class Stack
{
   private Object[] elements;
   private int top;

   /**
   Constructor to create a stack of Objects.
   @param size is the size of the stack.
   */
   public Stack(int size)
   {
      elements = new Object[size];
      top = 0;
   }

   /**
   Checks whether the stack is empty or if it is not empty.
   @return true if the top of the stack is equal to zero.
   */
   public boolean isEmpty()
   {
      return top == 0;
   }

   /**
   Checks whether the stack is full or if it is not full.
   @return true if the top of the stack is equal to the size of the stack
   */
   public boolean isFull()
   {
      return top == elements.length;
   }

   /**
   Pushes an Object onto the top of the stack.
   @param x is the Object that is pushed onto the top of the stack.
   */
   public void push(Object x)
   {
      elements[top++] = x;
   }

   /**
   Pops off the Object that is on the top of the stack.
   @return the Object which was popped off of the stack.
   */
   public Object pop()
   {
      return elements[--top];
   }

   public void clear()
   {
      for(int i = 0; i < elements.length; i++)
         elements[i] = null;
      top = 0;
   }


/**
Runs the main for Program 3
@author Mr. Scanlan
*/
public class Prog3
{
   /**
   Runs RpnEvaluator.
   @param args  is unused
   */
   public static void main (String args[])
   {
      try
      {
         RpnEvaluator rpne = new RpnEvaluator();
         rpne.run();
      }
      catch (Exception e)
      {
         System.out.println("Program Error!");
      }
   }
}

TEST DOC

示例输入:

 (4/12)  (2/10) - (40/1) * #
   (2/2)  (34/4) + #
(12/12)  (3/4) + (1/9) #
(2/3) (3/10) (-1/2) * -  #
(1/-1) (0/1) * (8/12) -     #
 (9/3)  #
   #
 (2/9)  (4/3) * (14/-12) - #
(2/9) B (4/3) / #
(1/2) (-1/3) (3/2) (-1/11) * * - #
  (1/2) + (2/2) #
(2/3)  (3/4) #
 (2/3) (8/9) - (3/2) * #
(12/2) (21/2) + +            #
(1/2) (-2/1) + (6/5) - #
  (2/3)  (472/1245)  (3434/12345) * - #
(10/20) (-20/10) + (65/-34) - (1212/1313) + #

对应的样本输出:(注意:有些行很长,但是 他们不包装。)

Expression 1 is: (1/3)(1/5)-(40/1)*
The value is: (16/3)
Intermediate results: (2/15)(16/3)
Expression 2 is: (1/1)(17/2)+
The value is: (19/2)
Intermediate results: (19/2)
Expression 3 is: (1/1)(3/4)+(1/9)
Invalid Expression
Intermediate results: (7/4)
Expression 4 is: (2/3)(3/10)(-1/2)*-
The value is: (49/60)
Intermediate results: (-3/20)(49/60)
Expression 5 is: (-1/1)(0/1)*(2/3)-
The value is: (-2/3)
Intermediate results: (0/1)(-2/3)
Expression 6 is: (3/1)
The value is: (3/1)
Intermediate results:
Expression 7 is:
Invalid Expression
Intermediate results:
Expression 8 is: (2/9)(4/3)*(-7/6)-
The value is: (79/54)
Intermediate results: (8/27)(79/54)
Expression 9 is: (2/9)B
Invalid Expression
Intermediate results:
Expression 10 is: (1/2)(-1/3)(3/2)(-1/11)**-
The value is: (5/11)
Intermediate results: (-3/22)(1/22)(5/11)
Expression 11 is: (1/2)+
Invalid Expression
Intermediate results:
Expression 12 is: (2/3)(3/4)
Invalid Expression
Intermediate results:
Expression 13 is: (2/3)(8/9)-(3/2)*
The value is: (-1/3)
Intermediate results: (-2/9)(-1/3)
Expression 14 is: (6/1)(21/2)++
Invalid Expression
Intermediate results: (33/2)
Expression 15 is: (1/2)(-2/1)+(6/5)-
The value is: (-27/10)
Intermediate results: (-3/2)(-27/10)
Expression 16 is: (2/3)(472/1245)(3434/12345)*-
The value is: (8625502/15369525)
Intermediate results: (1620848/15369525)(8625502/15369525)
Expression 17 is: (1/2)(-2/1)+(-65/34)-(12/13)+
The value is: (295/221)
Intermediate results: (-3/2)(7/17)(295/221)

1 个答案:

答案 0 :(得分:0)

我终于得到了你的问题: - )

我假设是

private Queue myQueue = new Queue(MAX_TOKEN);

你的意思是

private Queue myQueue = new ArrayDeque(MAX_TOKEN);

好吗?

问题是

获得此输入(&gt;表示sys.in)

>(2/9) B (4/3) / #
Expression 2 is: (2/9)B

>(1/2) (-1/3) (3/2) (-1/11) * * - #
Invalid Expression
Intermediate results: 
Expression 3 is: (-1/3)(3/2)(-1/11)**-
Invalid Expression
Intermediate results: (-3/22)(1/22)

因为你的程序处理每一行直到#,而你希望丢弃第一个表达式。似乎(1/2)正在消耗过程中。

错误消息显示

表达式3为:( - 1/3)(3/2)( - 1/11)** - ”

虽然不是,但应该是

表达式3是:(1/2)( - 1/3)(3/2)( - 1/11)**

右?

那么,如何中止无效令牌呢?像

        } else {
            throwLine(readIn);
            System.out.print(readIn);
            //valid = false;
            throw new Exception("invalid");
        }

private void doTypeCheck(String readIn, Fraction myFract, boolean valid,
        Fraction op1, Fraction op2, Fraction answer, int count) throws Exception {

private void runOnce(int count) throws Exception {

public void run() throws java.io.IOException {
    int count = 1;
    Fraction myInterMid;
    while (stdin.hasNext()) {
        try {
            runOnce(count++);
            System.out.print("Intermediate results: ");
            while (!myQueue.isEmpty()) {
                myInterMid = (Fraction) myQueue.remove();
                System.out.print(myInterMid.toString());
            }
            System.out.println();
        } catch (Exception e) {
            e.printStackTrace();
        }
        clear(myStack, myQueue);
    }
    System.out.println("Normal Termination of Program 3.");
}
相关问题