資源簡介
RPN計算器
Program Input
Each line of the input file (prob12.in) contains a series of numbers and operators. The program must evaluate these lines as RPN expressions. All tokens are separated by one or more spaces. Numbers may be negative. Valid operators are +(addition), -(subtraction), *(multiplication) and /(division). The last line of the file contains only the word END:
16 3 7 + *
4 32.125 13 – * 20 +
5 –3 * 4 2 / 6 3 1 – / + +
END
Program Output
The program will print the computed result of each RPN expression on a separate line.
160
96.5
-10
代碼片段和文件信息
import?java.io.*;
import?java.util.*;
public?class?RPNcalculator?{
public?static?void?main(String[]?args)?{
????String?fileName=“RPNInput.txt“;
????String?fileName2=“RPNOutput.txt“;
????Scanner?inputStream?=?null;
????PrintWriter?outputStream?=?null;
????//read
????try{
????????inputStream?=?new?Scanner(new?File(fileName));?//try?to?open?the?file
????}
????catch(Exception?e){
????????System.out.println(“Could?not?open?the?file?named?“+?fileName);?//?if?it?doesn‘t?find?it?tell?them
????????System.exit(0);??//?and?then?exit.
????}
????//write
????try{
????????outputStream?=?new?PrintWriter(new?FileOutputStream(fileName2true));?//try?to?create?the?file
????}
????catch(Exception?e){
????????System.out.println(“Could?not?open?the?file?named?“+?fileName2);?//?if?it?doesn‘t?find?it?tell?them
????????System.exit(0);??//?and?then?exit.
????}
????while(inputStream.hasNextLine()){
????????String?equation?=?inputStream.nextLine();
????????if?(equation==null)??break;
????????Stack?tks?=?new?Stack
評論
共有 條評論