Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.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
readIn()读取下一个元素和特定字符时出现Java问题_Java_String_Java.util.scanner - Fatal编程技术网

readIn()读取下一个元素和特定字符时出现Java问题

readIn()读取下一个元素和特定字符时出现Java问题,java,string,java.util.scanner,Java,String,Java.util.scanner,在字符串中找到特定字符后,如何添加空格?例子。。。。我想在该字符串中的“#”字符后添加一个空格。我还想知道,如果我的字符串中有多个“#”,我如何才能获得当前的职位 (2/9) B (4/3) / # (1/2) (-1/3) (3/2) (-1/11) * * - # (1/2) + (2/2) # 用同样的概念。我有一个像这样的循环。我还更新了字符串,使其看起来像我的问题。现在我的问题是,一旦我的循环处理并获取每个元素,如果它是一个错误的输入,例如(B,/,基本上是非操作数和“+”-“*”)

在字符串中找到特定字符后,如何添加空格?例子。。。。我想在该字符串中的“#”字符后添加一个空格。我还想知道,如果我的字符串中有多个“#”,我如何才能获得当前的职位

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

代码

   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();
      }
   }
}
分数

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;
   }

相应的示例输出:(注:有些行很长,但是 它们没有包装。)


我终于明白了你的问题:-)

我假设

private Queue myQueue = new Queue(MAX_TOKEN);
你是说

private Queue myQueue = new ArrayDeque(MAX_TOKEN);
好吗

问题是

当您获得此输入时(>表示sys.in)

因为您的程序处理每一行直到#,所以您希望第一个完整表达式被丢弃。在这个过程中,(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 Queue myQueue = new Queue(MAX_TOKEN);
private Queue myQueue = new ArrayDeque(MAX_TOKEN);
>(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)
        } 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.");
}