2015-03-30 46 views
1

我正在爲我的類建立一個簡單的RPN計算器,並且我創建了一個字符串方法,將輸入分爲令牌並將它們推入堆棧。該方法是完整的,它編譯,我的問題是,我不知道如何打印結果,無論如何有人可以幫助我呢?這是我的代碼。試圖打印Postfix計算器的結果

import java.util.*; 
import java.io.*; 
public class Program6 
{ 
    public static void main(String args[]) 
    { 
     System.out.println("Servando Hernandez"); 
     System.out.println("RPN command line calculator"); 
     Scanner scan = new Scanner(System.in); 
     compute(scan.nextLine()); 

    } 



    public static String compute(String input) 
    { 
     List<String> processedList = new ArrayList<String>(); 
     if (!input.isEmpty()) 
     { 
      StringTokenizer st = new StringTokenizer(input); 
      while (st.hasMoreTokens()) 
      { 
       processedList.add(st.nextToken()); 
      } 
     } 
     else 
     { 
      return "Error"; 
     } 
     Stack<String> tempList = new Stack<String>(); 

     Iterator<String> iter = processedList.iterator(); 

     while (iter.hasNext()) 
     { 
      String temp = iter.next(); 
      if (temp.matches("[0-9]*")) 
       { 

       tempList.push(temp); 
       } 
       else if (temp.matches("[*-/+]")) 
       { 

        if (temp.equals("*")) 
        { 
         int rs = Integer.parseInt(tempList.pop()); 
         int ls = Integer.parseInt(tempList.pop()); 
         int result = ls * rs; 
         tempList.push("" + result); 
        } 
        else if (temp.equals("-")) 
        { 
         int rs = Integer.parseInt(tempList.pop()); 
         int ls = Integer.parseInt(tempList.pop()); 
         int result = ls - rs; 
         tempList.push("" + result); 
        } 
        else if (temp.equals("/")) 
        { 
         int rs = Integer.parseInt(tempList.pop()); 
         int ls = Integer.parseInt(tempList.pop()); 
         int result = ls/rs; 
         tempList.push("" + result); 
        } 
        else if (temp.equals("+")) 
        { 
         int rs = Integer.parseInt(tempList.pop()); 
         int ls = Integer.parseInt(tempList.pop()); 
         int result = ls + rs; 
         tempList.push("" + result); 
        } 
       } 
       else 
       { 
        return "Error"; 
       } 
     } 

    return tempList.pop(); 
    } 
} 
+0

爲什麼不使用'System.out.println'? – fabian 2015-03-30 23:56:53

+0

要打印堆棧的頂層元素? – Servanh 2015-03-31 00:12:05

+0

想通了。 Thx – Servanh 2015-03-31 00:26:25

回答

0

修復它:這裏是。我忘了你只能打印方法....

System.out.print("> "); 
     String a = scan.nextLine(); 
     String b = "quit"; 
     String c = "mem"; 
     String d = "clear"; 
     if(a.equals(b)) 
     { 
      System.exit(0); 
     } 
     else 
     { 
      System.out.println(compute(a)); 
     } 
     System.out.print(">");