0

I have a file of lines with various integers and operations, how can I separate them and store them into an array so that I can use them with each other. For instance read a line 586+-, and perform (6+8)-5.

EDIT

Actually characters are separated by a space, should handle any integer. line would look like 5 8 6 + - or another one 10 50 30 * 6 + -

Pete
  • 3
  • 2

3 Answers3

1

If it's known that every input is a single digit (and there are no spaces), then parsing the file is pretty simple:

while(has more lines){
    nextLine = read line
    for each char c in nextLine
        parse character into digit or operation
}

In Java, you can do that with a Scanner or a BufferedReader. Scanner has a Scanner.hasNextLine() method. In the case of BufferedReader, you would do something like:

final BufferedReader br = new BufferedReader(new FileReader(fileName));
while((nextLine = br.readLine()) != null){
    ...
}

(see BufferedReader.readLine())

There are several ways to parse the characters into your symbols. For getting the digit, first test to make sure it is a digit:

boolean isDigit(final char c){
    return c >= '0' && c <= '9';
}

If it is a digit, then find its value:

int getDigit(final char digit){
    return digit - '0';
}

Otherwise, if it's an operation, then you need to use a switch statement to figure out what operation it is:

int getOp(final char c){
    switch(c){
    case OP1_CHAR : return OP1_CODE;
    case OP2_CHAR : return OP2_CODE;
    ...
    default: throw new RuntimeException(c + " is an unknown operation");
    }
}

Since an operation causes you to pop from your stack, you don't really need to this intermediate step of assigning on OP_CODE rather you can just switch on your OP_CHAR and then do the required operation...something like:

void doOp(final char op){
    switch(c){
    case OP1_CHAR : perform operation 1 which probably requires 
                        popping from the stack, doing some operation,
                        and pushing back onto the stack
        break; // or return;

    case OP2_CHAR : perform operation 2
        break;
    ...
    default: throw new RuntimeException(op + " is an unknown operation");
    }
}
Jared
  • 940
  • 5
  • 9
  • So how would i go about parsing each character into digit or operation, thats where I am truly stuck – Pete Nov 28 '14 at 23:59
  • i forgot to put spaces, there are spaces, it also needs to be able to handle double digits – Pete Nov 29 '14 at 00:25
  • @Pete It would have been nice to have said that when peter.petrov specifically asked it in the question comments rather than commenting that it's single digits. – Jared Nov 29 '14 at 00:28
  • @Pete Other than reading the tokens, the only thing that would change is that I would suggest using [`Integer.parseInt(token)`](https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String)) to read the integer value (or `Double.parseDouble(token)` if you're going to accept decimal values) and catch the `NumberFormatException` to determine it's an operation, then it would be the same code except you switch on the token `String` over all of the op strings (which I believe is possible since Java 7). – Jared Nov 29 '14 at 00:53
0

You have postfix (also called reverse Polish notation) expressions given in that file.
So your task is to parse them first in order to compute the results from them.
To implement this in code you need to know the algorithm for doing it.
See e.g. Postfix notation to expression tree
You may also google for "parsing postfix expressions". There're plenty of resources.

Community
  • 1
  • 1
peter.petrov
  • 38,363
  • 16
  • 94
  • 159
-1

The Solution:

Operations.txt contains the list of numbers separated by spaces:

5 8 6 + +

10 50 30 * 6 + -

.......

Here the code:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner; 
public class Operations {
static String[] stack = new String[100];
static int index=-1;

public static void main(String[] args) throws FileNotFoundException, IOException {       
    File f = new File ("C:\\Operations.txt");
    Scanner input = new Scanner(f);               
    String line;        
    while(input.hasNextLine())
    {
        line = input.nextLine();
        String [] opes = line.split("\\s+");      
        for(int i=0; i<opes.length;i++) {                
            if (opes[i].matches("[\\*+-/]")) {                     
                push(calculate(opes[i]));
            }
            else    
                push(opes[i]);
        }
        System.out.println(line+" = "+pop());
    }        
}

public static void push(String value) {
    index++;
    stack[index]=value;        
}

public static String pop() {        
    String value = stack[index];
    index--;
    return value;
}

public static String calculate(String operation) {
    double res = 0.0;
    double ope1=Double.parseDouble(pop());
    double ope2=Double.parseDouble(pop());
    switch (operation) {
        case "+": res = ope1 + ope2;
            break;
        case "-": res = ope1 - ope2;    
            break;
        case "*": res = ope1 * ope2;    
            break;
        case "/": res = ope1 / ope2;    
            break;    
    }
    return String.valueOf(res);
  }    
}
SkyMaster
  • 1,323
  • 1
  • 8
  • 15