다양한 정수 및 연산을 가진 파일이 있는데,이를 어떻게 분리하여 배열에 저장할 수있어서 서로간에 사용할 수 있습니다. 예를 들어 라인 586 + -을 읽고 (6 + 8) -5를 수행하십시오.정수 및 연산을 배열에 저장하십시오.
편집
사실 문자가 공백으로 구분, 정수를 처리해야합니다. 라인은 5 8 6+처럼 보일 것입니다 - 또는 다른 하나 10 50 30 * 6 + -
다양한 정수 및 연산을 가진 파일이 있는데,이를 어떻게 분리하여 배열에 저장할 수있어서 서로간에 사용할 수 있습니다. 예를 들어 라인 586 + -을 읽고 (6 + 8) -5를 수행하십시오.정수 및 연산을 배열에 저장하십시오.
편집
사실 문자가 공백으로 구분, 정수를 처리해야합니다. 라인은 5 8 6+처럼 보일 것입니다 - 또는 다른 하나 10 50 30 * 6 + -
는 다음 파일을 구문 분석하는 것은 매우 간단하다 :
while(has more lines){
nextLine = read line
for each char c in nextLine
parse character into digit or operation
}
자바에서, 당신이 할 수있는 Scanner
또는 BufferedReader
. Scanner
은 Scanner.hasNextLine()
방법을 사용합니다.
final BufferedReader br = new BufferedReader(new FileReader(fileName));
while((nextLine = br.readLine()) != null){
...
}
(BufferedReader.readLine()
참조)
이 문자로 문자를 구문 분석하는 방법에는 여러 가지가 있습니다 BufferedReader
의 경우, 당신은 뭔가를 할 것입니다. 숫자를 얻기 위해, 첫 번째 테스트를 만들기 위해 그것을 가 숫자 있는지 : 그것은 작업의 경우, 그렇지 않으면
int getDigit(final char digit){
return digit - '0';
}
: 그것은 가 숫자 경우, 그 값을 찾을 수
boolean isDigit(final char c){
return c >= '0' && c <= '9';
}
스위치 문을 사용하여 어떤 연산인지 파악해야합니다.
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");
}
}
스택에서 튀어 오르기 위해서는 OP_CODE에 할당하는 중간 단계가 필요하지 않습니다. OP_CHAR을 켜고 필요한 작업을 수행 할 수 있습니다.뭔가 같은 :
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");
}
}
당신은 그 파일에 주어진 후위 식 (역 폴란드어 표기법이라고도 함)이 있습니다.
그러면 결과를 계산하기 위해 먼저 구문 분석해야합니다.
코드에서이를 구현하려면 알고리즘을 알아야합니다.
예 : Postfix notation to expression tree
"구문 분석 후행 표현"에 대해 Google을 사용할 수도 있습니다. 많은 자원이 있습니다. 이 모든 입력이 한 자리 것으로 알려져 (그리고 공백이 없음) 인 경우
솔루션 :
5 8 6 + +
10 50 30 * 6 + -
.......
Operations.txt
공백으로 구분 된 숫자의 목록이 포함되어 있습니다
여기에 코드 :
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);
}
}
86 * 5는 어떻게 표시해야합니까? – Jared
아마도 OP의 표현은 문제를 모호하지 않게 만드는 1 자리 숫자로만 제한됩니다. @Pete 맞지? –