简体   繁体   中英

Java Reading Lines and Doing Math Equations

So I have this project to do, that I need to read a text file named Input, and I'm doing it like this:

    public static void textParser() {
    File inputFile = new File("Input.txt");
    try {
        BufferedReader br = new BufferedReader(new FileReader(inputFile));
        String inputsText;
        while ((inputsText = br.readLine()) != null) {
            System.out.println(inputsText);
        }
        br.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

and it works. Inside of Input.txt, it shows:

6
10 + 4
12 - 3
1000 / 50
9 * 64
2^5
90 % 8
1 + 1
6 * 4

The first line (6) will always be the amount of equations to-do, can be different than 6. Then I have to do how many equations the first line says to, how would I go on doing that? Thanks!

You need to write a parser. Without doing your homework for you this is the pseudo-code that should be sufficient:

for line in ReadFile()  
{  
  for token in split(line,expression)  
  {  
      if token is digit  
         digits.enqueue(token) 
      if token is symbol  
         symbols.enqueue(token)    
  }  
     for element in digits,symbols:   
         applySymbol(firstDigit,secondDigit,symbol)
}  

I've solved this problem a couple times in different languages. Look into the Shunting-yard algorithm

Basically you push and pop operators and operands onto a priority queue. You're basically converting infix to post-fix. Once your equation is in post-fix notation its much easier to solve.

If you don't have order of precedence to worry about the problem is much simpler but can still be solved by the same approach.

Edit:

We humans use in fix notation: 3 + 5 - 1 The operators are between the operands.

In Post fix notation looks like this: 3 5 + 1 -

The operators appear after the operands. Equations written this way are easy to evaluate. You just push operands onto a stack, then evaluate the last 2 using the next operator. So here, you'd push 3, and 5 onto a stack. Then you encounter + operator, so you add 3 and 5, get 8. Push 8 onto stack. now you read 1. Push 1 onto stack. Now you read -. Subtract 8 from 1. You get an answer of 7.

The shunting yard algorithm tells you how to convert between infix to post fix.

Good luck!

一种选择是使用ANTLR生成解析器,本教程几乎涵盖了您尝试做的事情

First you need to store them in a array of strings

Then get the first element in the array and convert it to an integer.

Based on the integer value the loop has to be iterated. so loop is formed. now you need to start reading the string array from the next index.

For doing the arithmetic operations first you need to have an array of 4 chars '+','-','*','%'

split the string based on the char array. this you can do it as a separate function. since for everytime it needs to get called. for performance i am saying.

Then you will get the two values parsed and their operator which splits them.

now you can perform the arithmetic operations.

thats it you got the required.

I have finally figured it out a different way that works, here is how I'm doing it:

    public static void textParser() {
    File inputFile = new File("Input.txt");
    try {
        Scanner scanner = new Scanner(inputFile);
        int numberOfQuestions = Integer.parseInt(scanner.next());
        for (int i = 1; i <= numberOfQuestions; i++) {
            int firstInt = Integer.parseInt(scanner.next());
            String operationSign = scanner.next();
            int secondInt = Integer.parseInt(scanner.next());
            if (operationSign.contains("+")) {
                int answer = firstInt + secondInt;
                System.out.println("Equation " + i + " : " + firstInt
                        + " + " + secondInt + " = " + answer);
            } else if (operationSign.contains("-")) {
                int answer = firstInt - secondInt;
                System.out.println("Equation " + i + " : " + firstInt
                        + " - " + secondInt + " = " + answer);
            } else if (operationSign.contains("/")) {
                int answer = firstInt / secondInt;
                System.out.println("Equation " + i + " : " + firstInt
                        + " / " + secondInt + " = " + answer);
            } else if (operationSign.contains("*")) {
                int answer = firstInt * secondInt;
                System.out.println("Equation " + i + " : " + firstInt
                        + " * " + secondInt + " = " + answer);
            } else if (operationSign.contains("%")) {
                int answer = firstInt % secondInt;
                System.out.println("Equation " + i + " : " + firstInt
                        + " % " + secondInt + " = " + answer);
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

Thank you to everyone for helping!

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