迴圈-17. 簡單計算機(20)

來源:互聯網
上載者:User

題目來源:

類比簡單運算器的工作。假設計算機只能進行加減乘除運算,運算數和結果都是整數,4種運算子的優先順序相同,按從左至右的順序計算。

輸入格式:

輸入在一行中給出一個四則運算算式,沒有空格,且至少有一個運算元。遇等號”=”說明輸入結束。

輸出格式:

在一行中輸出算式的運算結果,或者如果除法分母為0或有非法運算子,則輸出錯誤資訊“ERROR”。 輸入範例:

1+2*10-10/2=
輸出範例:
10
解法:

import java.util.Scanner;public class Main {public static void main(String[] args){Scanner scanner = new Scanner(System.in);String OPE=  "+-*/=";//獲得運算式String expression = scanner.next();//是否已有操作符boolean haveOperator =false;//暫存運算元StringBuilder stroperand = new StringBuilder();//運算元int operand1=0 ;int operand2=0 ;//暫存上一個操作符char operator=' ';//遍曆運算式for(int i=0;i<expression.length();i++){try{char c = expression.charAt(i);//如果是數字,加到stroperand後if(  OPE.indexOf(c)<0){stroperand.append(c);}//如果是操作符else{//將stroperand中的字串轉換成數字 int temp = Integer.valueOf(stroperand.toString());//stroperand清空stroperand.delete(0, stroperand.length());//判斷是否有操作符if(!haveOperator){//無,將數字存入到operand1中operand1 = temp;}else{//有,將數字存入到operand2中operand2 = temp;//讓operand1 = operand1 操作符 operand2int index = OPE.indexOf(operator);switch(index){case 0:operand1 = operand1 + operand2;break;case 1: operand1 = operand1 - operand2;break;case 2: operand1 = operand1 * operand2;break;case 3:operand1 = operand1 / operand2;break;}}haveOperator =true;operator =c;//如果操作符號是否是 = if(operator=='='){System.out.println(operand1);return ;}}}catch(Exception e){System.out.println("ERROR");}} }}              


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.