前缀表达式

题目

问题描述
  编写一个程序,以字符串方式输入一个前缀表达式,然后计算它的值。输入格式为:“运算符 对象1 对象2”,其中,运算符为“+”(加法)、“-”(减法)、“*”(乘法)或“/”(除法),运算对象为不超过10的整数,它们之间用一个空格隔开。要求:对于加、减、乘、除这四种运算,分别设计相应的函数来实现。
  输入格式:输入只有一行,即一个前缀表达式字符串。
  输出格式:输出相应的计算结果(如果是除法,直接采用c语言的“/”运算符,结果为整数)。
  输入输出样例
样例输入
+ 5 2
样例输出
7

源码

import java.util.*;
public class Main {
    public static void main(String[] args) {
      Scanner sc=new Scanner(System.in);
      while(sc.hasNext()){
          String sz=sc.nextLine();
          String[] ch=sz.split(" ");
          int num1=Integer.parseInt(ch[1]);
          int num2=Integer.parseInt(ch[2]);
          if(ch[0].equals("+"))
              System.out.println(num1+num2);
          else if(ch[0].equals("-"))
              System.out.println(num1-num2);
          else if(ch[0].equals("*"))
              System.out.println(num1*num2);
          else if(ch[0].equals("/"))
              System.out.println(num1/num2);
      }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章