1 package Test; 2 import java.util.Scanner; 3 /** 4 * 设计一个计算器,实现多行输入,并分别输出结果 5 * 输入: 6 * 4/2+5+9*7-9 7 * 3*2+8/2-7+2 8 * 3+8*4-5+3+1 9 * 9/4/2+7-6-1 10 * 输出: 11 * 61 12 * 5 13 * 34 14 * @author litaiqing 15 * 16 */ 17 public class Test { 18 public static void main(String[] args) { 19 Scanner scanner = new Scanner(System.in); 20 while(scanner.hasNext()){ 21 String in = scanner.nextLine(); 22 System.out.println(calc(in)); 23 } 24 } 25 public static int calc(String in){ 26 int result = 1; 27 if(in.contains("+")){ 28 String[] nums = in.split("\\+"); 29 result = calc(nums[0]); 30 for(int i = 1; i < nums.length; i++){ 31 result += calc(nums[i]); 32 } 33 }else if(in.contains("-")){ 34 String[] nums = in.split("\\-"); 35 result = calc(nums[0]); 36 for(int i = 1; i < nums.length; i++){ 37 result -= calc(nums[i]); 38 } 39 }else if(in.contains("*")){ 40 String[] nums = in.split("\\*"); 41 result = calc(nums[0]); 42 for(int i = 1; i < nums.length; i++){ 43 result *= calc(nums[i]); 44 } 45 }else if(in.contains("/")){ 46 String[] nums = in.split("/"); 47 result = calc(nums[0]); 48 for(int i = 1; i < nums.length; i++){ 49 result /= calc(nums[i]); 50 } 51 }else{ 52 result = Integer.parseInt(in); 53 } 54 return result; 55 } 56 }
输出
4/2+5+9*7-9
61
3*2+8/2-7+2
5
3+8*4-5+3+1
34
9/4/2+7-6-1
1
时间: 2024-10-13 02:36:24