2014년 1월 10일 금요일

import java.util.Scanner;
import java.util.Stack;

public class Calc1 {
// 일단은 중위표현식을 후위표현식으로 만드는 프로그램 작성
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Stack<Character> stack = new Stack<Character>();

while(true){
System.out.println("수식을 입력하세요(0은 종료)");
String exp = sc.nextLine();
if(exp.equals("0")) break;

String result="";
for(int i=0;i<exp.length();i++){
// 1) 입력받은 중위 표기식에서 토큰을 읽는다.
char ch = exp.charAt(i);
// 2) 토큰이 피연산자이면 토큰을 결과에 출력한다.
if(ch>='0' && ch<='9' || ch=='.')
result += ch;
else if("+-*/()".contains(ch+"")){
result += ' '; // 연산자이면 숫자들을 구분하기 위하여 공백삽입
if(stack.isEmpty()) // 스텍이 비어 있으면
stack.push(ch);
else if(ch=='(')    // ((여는괄호)이면 스텍에 넣기
stack.push(ch);
else if(ch==')'){    // )(닫는괄호)이면 (가 나올때까지 꺼낸다.
while(!stack.isEmpty()){
char t = stack.pop();
if(t=='(') break;
result += t;
}
}else{
// 스텍에 있는 연산순서가 높거나 같은것을 모두 출력한다.
while(!stack.isEmpty() && getPriority(stack.peek())>=getPriority(ch)){
result += stack.pop();
}
stack.push(ch); // 자신이 들어가고
}
}
}
// 스텍에 남은 연산자를 모두 꺼내어 출력한다.
while(!stack.isEmpty()) result += stack.pop();
System.out.println(exp + " : " + result);

// 이제 후위 표현식을 읽어서 계산한다.
Stack<Double> stack2 = new Stack<Double>();

// 1글자씩 읽어 숫자면 스텍에 넣고 연산자이면 스텍에서 두개를 꺼내
// 연산하고 다시 넣는다.
for(int i=0;i<result.length();i++){
char t = result.charAt(i); // 한글자읽고
if(t>='0' && t<='9' || t=='.'){
String temp = t+"";
while(i<result.length()){
t = result.charAt(++i);
if(!(t>='0' && t<='9' || t=='.')){--i; break;}
temp += t;
}
stack2.push(Double.parseDouble(temp));
}else if("+-*/".contains(t+"")){
if(!stack2.isEmpty()){
double n1 = stack2.pop();
double n2 = stack2.pop();
double r=0;
switch(t){
case '+':
r = n2 + n1;
break;
case '-':
r = n2 - n1;
break;
case '*':
r = n2 * n1;
break;
case '/':
r = n2 / n1;
break;
}
stack2.push(r);
}
}
}
System.out.println("답 : " + stack2.pop());
}
}
public static int getPriority(char op){
int result=0;
switch(op){
case '+':
case '-':
result = 1;
break;
case '*':
case '/':
result = 2;
break;
}
return result;
}
}

댓글 없음:

댓글 쓰기