fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. import java.util.Scanner;
  8.  
  9. class LinkedStack {
  10.  
  11. public class StackNode{
  12. int data;
  13. StackNode link;
  14. }
  15. private StackNode top;
  16.  
  17. public boolean isEmpty(){
  18. return (top == null);
  19. }
  20.  
  21. public void push(int item){
  22. StackNode newNode = new StackNode();
  23. newNode.data = item;
  24. newNode.link = top;
  25. top = newNode;
  26. }
  27.  
  28. public int pop() throws IntegerStackEmptyException{
  29. if(isEmpty()){
  30. throw new IntegerStackEmptyException("수식 형식이 잘못되었습니다.");
  31. }
  32. else{
  33. int item = top.data;
  34. top = top.link;
  35. return item;
  36. }
  37. }
  38. public class IntegerStackEmptyException extends Exception {
  39. public IntegerStackEmptyException(String message) {
  40. super(message);
  41. }
  42. }
  43.  
  44. public static class PostFix {
  45.  
  46. private String exp;
  47.  
  48. public int evalPostfix(String postfix) throws IntegerStackEmptyException{
  49. LinkedStack s= new LinkedStack();
  50. exp = postfix;
  51. int op1,op2,value;
  52. char testCh;
  53. for(int i=0; i<7;i++){
  54. testCh = exp.charAt(i);
  55. if(testCh !='+' && testCh != '-' &&
  56. testCh!='*' && testCh !='/'){
  57. value = testCh - '0';
  58. s.push(value);
  59. }
  60. else{
  61. op2 = s.pop();
  62. op1 = s.pop();
  63. switch(testCh){
  64. case'+' : s.push(op1 + op2); break;
  65. case'-' : s.push(op1 - op2); break;
  66. case'*' : s.push(op1 * op2); break;
  67. case'/' : s.push(op1 / op2); break;
  68. }
  69. }
  70.  
  71. }
  72. return s.pop();
  73. }
  74. public static void main(String[] args) throws IntegerStackEmptyException{
  75. // TODO Auto-generated method stub
  76.  
  77.  
  78. Scanner scan = new Scanner(System.in);
  79. PostFix o = new PostFix();
  80.  
  81. System.out.print("후위 표기정수 수식 입력:");
  82. String result = scan.next();
  83.  
  84. System.out.println("결과: "+o.evalPostfix(result));
  85. }
  86.  
  87. }
  88. }
Runtime error #stdin #stdout #stderr 0.09s 380736KB
stdin
Standard input is empty
stdout
후위 표기정수 수식 입력:
stderr
Exception in thread "main" java.util.NoSuchElementException
	at java.util.Scanner.throwFor(Scanner.java:907)
	at java.util.Scanner.next(Scanner.java:1416)
	at LinkedStack$PostFix.main(Main.java:82)