導航:首頁 > 編程語言 > java計算加減乘除

java計算加減乘除

發布時間:2022-08-24 21:10:46

『壹』 加減乘除運算(java)

實際上這相當於javascript的eval方法,以下是該方法的java實現:

//Eval.java
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class Eval {
public int eval(String exp){
List<String> list = infixExpToPostExp(exp);//轉化成後綴表達式
return doEval(list);//真正求值
}

//遇到操作符壓棧,遇到表達式從後綴表達式中彈出兩個數,計算出結果,壓入堆棧
private int doEval(List<String> list) {
Stack<String> stack = new Stack<String>();
String element;
int n1,n2,result;
try{
for(int i = 0; i < list.size();i++){
element = list.get(i);
if(isOperator(element)){
n1 = Integer.parseInt(stack.pop());
n2 = Integer.parseInt(stack.pop());
result = doOperate(n1,n2,element);
stack.push(new Integer(result).toString());
}else{
stack.push(element);
}
}
return Integer.parseInt(stack.pop());
}catch(RuntimeException e){
throw new IllegalExpressionException(e.getMessage());
}
}

private int doOperate(int n1, int n2, String operator) {
if(operator.equals("+"))
return n1 + n2;
else if(operator.equals("-"))
return n1 - n2;
else if(operator.equals("*"))
return n1 * n2;
else
return n1 / n2;
}

private boolean isOperator(String str){
return str.equals("+") || str.equals("-") || str.equals("*") || str.equals("/");
}

private List<String> infixExpToPostExp(String exp){//將中綴表達式轉化成為後綴表達式
List<String> postExp = new ArrayList<String>();//存放轉化的後綴表達式的鏈表
StringBuffer numBuffer = new StringBuffer();//用來保存一個數的
Stack<Character> opStack = new Stack<Character>();//操作符棧
char ch,preChar;
opStack.push('#');
try{
for(int i = 0; i < exp.length();){
ch = exp.charAt(i);
switch(ch){
case '+':
case '-':
case '*':
case '/':
preChar = opStack.peek();
// 如果棧裡面的操作符優先順序比當前的大,則把棧中優先順序大的都添加到後綴表達式列表中
while(priority(preChar) >= priority(ch)){
postExp.add(""+preChar);
opStack.pop();
preChar = opStack.peek();
}
opStack.push(ch);
i++;
break;
case '(':
// 左括弧直接壓棧
opStack.push(ch);
i++;
break;
case ')':
// 右括弧則直接把棧中左括弧前面的彈出,並加入後綴表達式鏈表中
char c = opStack.pop();
while(c != '('){
postExp.add("" + c);
c = opStack.pop();
}
i++;
break;
// #號,代表表達式結束,可以直接把操作符棧中剩餘的操作符全部彈出,並加入後綴表達式鏈表中
case '#':
char c1;
while(!opStack.isEmpty()){
c1 = opStack.pop();
if(c1 != '#')
postExp.add("" + c1);
}
i++;
break;
//過濾空白符
case ' ':
case '\t':
i++;
break;
// 數字則湊成一個整數,加入後綴表達式鏈表中
default:
if(Character.isDigit(ch)){
while(Character.isDigit(ch)){
numBuffer.append(ch);
ch = exp.charAt(++i);
}
postExp.add(numBuffer.toString());
numBuffer = new StringBuffer();
}else{
throw new IllegalExpressionException("illegal operator");
}
}
}
}catch(RuntimeException e){
throw new IllegalExpressionException(e.getMessage());
}
return postExp;
}

private int priority(char op){//定義優先順序
switch(op){
case'+':
case'-':
return 1;
case'*':
case'/':
return 2;
case'(':
case'#':
return 0;
}
throw new IllegalExpressionException("Illegal operator");
}

}

Main.java 主函數所在類
public class Main
{
public static void main(String[] args) {

try {
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
String exp=br.readLine();

int result = eval.eval(exp);
System.out.println(result);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}

IllegalExpressionException異常類
public class IllegalExpressionException extends RuntimeException{

public IllegalExpressionException(){

}

public IllegalExpressionException(String info){
super(info);
}
}

『貳』 java中簡單的加減乘除運算

在a.jsp中寫如下代碼:

請輸入
<form action="b.jsp" method="post">
上課作業比率:<input type="text" name="zy" /> <br />
上課實訓:<input type="text" name="sksx" /> <br />
平時考勤: <input type="text" name="kq" /> <br />
平時實訓:<input type="text" name="pssx" /> <br />
</form>

b.jsp中..
<%String s = request.getParameter("zy")
//.......
%>

懶得寫了太麻煩@_@

『叄』 java加減乘除是什麼類

java中實現加減乘除的類是java.math.BigDecimal類. BigDecimal 類提供以下操作:算術、標度操作、舍入、比較、哈希演算法和格式轉換。

加法運算:調用BigDecimal類的add方法即可

BigDecimalb1=newBigDecimal("1");
BigDecimalb2=newBigDecimal("2");
BigDecimalresult=b1.add(b2);//加法
System.out.println(result);

減法運算:調用BigDecimal類的subtract方法即可

BigDecimalb1=newBigDecimal(3.2);
BigDecimalb2=newBigDecimal(1.6);
BigDecimalresult=b1.subtract(b2);//減法
System.out.println(result);

乘法運算:調用BigDecimal類的multiply方法即可

BigDecimalb1=newBigDecimal(9);
BigDecimalb2=newBigDecimal(8.2);
BigDecimalresult=b1.multiply(b2);//乘法
System.out.println(result);

除法運算:調用BigDecimal類的divide方法即可。

注意: 除法運算存在除不盡的情況,比如1.0/3=0.333333.. 我們需要指定小數點後面的長度,以及有效的舍入模式(例如四捨五入模式).

BigDecimalb1=newBigDecimal("1");
BigDecimalb2=newBigDecimal("3");
intscale=5;//scale指定小數點後面的位數為5位
doubleresult=b1.divide(b2,scale,BigDecimal.ROUND_HALF_UP).doubleValue();//除法
//BigDecimal.ROUND_HALF_UP表示四捨五入
System.out.println(result);

備註:

1:BigDecimal的構造參數有很多,但浮點類型建議轉換成字元串類型, 避免精度的丟失.

doubled1=0.001;//浮點類型
Strings1=Double.toString(d1);//轉成字元串
BigDecimalb1=newBigDecimal(s1);//使用字元串作為構造參數

2:BigDecimal類, 內存佔用比基本類型多,並且為了計算的精度,速度比double慢一點.所以,只有在需要精確計算的情況下,才使用BigDecimal類進行. 普通運算,還是多使用+-*/運算符,位運算符等.

『肆』 如何使用java實現加減乘除運算

publicclasstest{publicstaticvoidmain(String[]args){inta=5;intb=1;intc=a+b;intd=a-b;inte=a*b;intf=a/c;System.out.println(c,d,e,f);}}

『伍』 Java的加減乘除問題

//JAVA編程:四則運算(接收用戶輸入的2個操作數,和運算符),計算之後,輸出結果~~~~
import java.util.Scanner;
public class 四則運算 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("請輸入第一個數字:");
int a = sc.nextInt();
System.out.print("請輸入運算符號:");
String str = sc.next();
char ch = str.charAt(0);
System.out.print("請輸入第二個數字:");
int b = sc.nextInt();
switch(ch)
{
case '+':
System.out.println(a+"+"+ b + "="+(a+b));
break;
case '-':
System.out.println(a+"-"+ b+ "="+(a-b));
break;
case '*':
System.out.println(a+"*"+ b+ "="+(a*b));
break;
case '/':
if(b==0){
System.out.println("被除數為零,運算無意義!");
break;
}
else {
System.out.println(a+"/"+ b+ " = "+(a/b));
break;
}
default:
System.out.println("運算符是無意義字元!");
break;
}
}
}

望採納~~~~~~~~

『陸』 java的加減乘除運算

使用BigDecimal並且一定要用String來夠造。
實現方法如下:

import java.math.BigDecimal;

/**

* 由於Java的簡單類型不能夠精確的對浮點數進行運算,這個工具類提供精

* 確的浮點數運算,包括加減乘除和四捨五入。

*/

public class Arith{

//默認除法運算精度

private static final int DEF_DIV_SCALE = 10;

//這個類不能實例化

private Arith(){

}

/**

* 提供精確的加法運算。

* @param v1 被加數

* @param v2 加數

* @return 兩個參數的和

*/

public static double add(double v1,double v2){

BigDecimal b1 = new BigDecimal(Double.toString(v1));

BigDecimal b2 = new BigDecimal(Double.toString(v2));

return b1.add(b2).doubleValue();

}

/**

* 提供精確的減法運算。

* @param v1 被減數

* @param v2 減數

* @return 兩個參數的差

*/

public static double sub(double v1,double v2){

BigDecimal b1 = new BigDecimal(Double.toString(v1));

BigDecimal b2 = new BigDecimal(Double.toString(v2));

return b1.subtract(b2).doubleValue();

}

/**

* 提供精確的乘法運算。

* @param v1 被乘數

* @param v2 乘數

* @return 兩個參數的積

*/

public static double mul(double v1,double v2){

BigDecimal b1 = new BigDecimal(Double.toString(v1));

BigDecimal b2 = new BigDecimal(Double.toString(v2));

return b1.multiply(b2).doubleValue();

}

/**

* 提供(相對)精確的除法運算,當發生除不盡的情況時,精確到

* 小數點以後10位,以後的數字四捨五入。

* @param v1 被除數

* @param v2 除數

* @return 兩個參數的商

*/

public static double div(double v1,double v2){

return div(v1,v2,DEF_DIV_SCALE);

}

/**

* 提供(相對)精確的除法運算。當發生除不盡的情況時,由scale參數指

* 定精度,以後的數字四捨五入。

* @param v1 被除數

* @param v2 除數

* @param scale 表示表示需要精確到小數點以後幾位。

* @return 兩個參數的商

*/

public static double div(double v1,double v2,int scale){

if(scale<0){

throw new IllegalArgumentException(

"The scale must be a positive integer or zero");

}

BigDecimal b1 = new BigDecimal(Double.toString(v1));

BigDecimal b2 = new BigDecimal(Double.toString(v2));

return b1.divide(b2,scale,BigDecimal.ROUND_HALF_UP).doubleValue();

}

/**

* 提供精確的小數位四捨五入處理。

* @param v 需要四捨五入的數字

* @param scale 小數點後保留幾位

* @return 四捨五入後的結果

*/

public static double round(double v,int scale){

if(scale<0){

throw new IllegalArgumentException(

"The scale must be a positive integer or zero");

}

BigDecimal b = new BigDecimal(Double.toString(v));

BigDecimal one = new BigDecimal("1");

return b.divide(one,scale,BigDecimal.ROUND_HALF_UP).doubleValue();

}

};

『柒』 java做一個簡單的加減乘除運算,用鍵盤先後輸入a,b的數值。

//參考下我剛寫的這個,稍顯得智能一些!你可以稍加更改;思路都注釋的很詳細了!
//代碼也不算多,
importjava.util.Scanner;
publicclass計算器{
privatestaticScannersc=newScanner(System.in);
publicstaticvoidmain(String[]args){
init();
}
privatestaticvoidinit(){
while(true)
sop(input());
}
privatestaticStringinput(){
sop("請輸入運算表達式如:1+1回車!");
Stringstr=sc.nextLine(),sum="";
chartem=0;
intpoin=0;
for(inti=0;i<str.length();i++){//遍歷!
charcs=str.charAt(i);
if(cs=='+'||cs=='-'||cs=='*'||cs=='/'){//尋找找運算符號
tem=str.charAt(i);//記錄運算符號!
poin=i;//記錄符號位置!
break;
}elseif(i>=str.length()-1){
sop("輸入不合法請檢查!");
init();
}
}//拆分數字!
doublea=Double.parseDouble(str.substring(0,poin));
doubleb=Double.parseDouble(str.substring(poin+1));
switch(tem){//開始判斷運算!
case'+':
sum=""+(a+b);
break;
case'-':
sum=""+(a-b);
break;
case'*':
sum=""+(a*b);
break;
default:
sum=""+(a/b);
break;
}
returnstr+"="+sum;
}//列印功能!
privatestaticvoidsop(Objectobj){
System.out.println(obj);
}
}

『捌』 java加減乘除計算器界面編程

來源:Code Wizards HQ

智能觀 編譯

孩子想學編碼的話,有很多方法可以展開學習。可以讓他們學著構建視頻游戲、創建動畫、開發移動應用程序和搭建網站。不管孩子喜歡哪種形式,都有大量的編碼書供他們快速學起來!

但是,怎麼才能找到一本好的兒童編碼書呢?


『玖』 java如何實現3個 個位數的加減乘除運算

publicclassParamDemo{
publicstaticvoidmain(String[]args){
Map<String,Integer>map=newHashMap<>();
map.put("+",1);
map.put("-",1);
map.put("*",2);
map.put("/",2);

Scannerscanner=newScanner(System.in);
intnum1=scanner.nextInt();
intnum2=scanner.nextInt();
intnum3=scanner.nextInt();

Stringop1=scanner.next();
Stringop2=scanner.next();

//此時證明第一個操作符優先順序大於第二個操作符
if(map.get(op1)-map.get(op2)>=0){
inttmpNumber=operateNum(op1,num1,num2);
System.out.println(operateNum(op2,tmpNumber,num3));
}else{
inttmpNumber=operateNum(op2,num2,num3);
System.out.println(operateNum(op1,num1,tmpNumber));
}

scanner.close();
}

privatestaticintoperateNum(Stringoperator,intnum1,intnum2){

switch(operator){
case"+":
returnnum1+num2;
case"-":
returnnum1-num2;
case"*":
returnnum1*num2;
case"/":
returnnum1/num2;
default:
return0;
}

}


}

『拾』 如何使用Java對象語言編寫一個加減乘除計算器要有代碼

下面文件名要為:JiSuanQi.java

importjava.awt.*;

importjava.awt.event.*;

publicclassJiSuanQi

{

Strings="",s1=null,s2=null;

Framef=newFrame("計算器");

TextFieldtf=newTextField(30);

Panelp1=newPanel();

Panelp2=newPanel();

Panelp3=newPanel();

Buttonbt1=newButton("=");

Buttonbt2=newButton("刪除");

Button[]bt=newButton[16];

intid=0;

publicstaticvoidmain(String[]args)

{

newJiSuanQi().init();

}

publicvoidinit()

{

f.setBackground(newColor(85,247,253));

f.setLayout(newBorderLayout(4,4));

p2.setLayout(newGridLayout(4,4,4,4));

p3.setLayout(newBorderLayout(4,4));

f.setResizable(false);

f.add(p1,BorderLayout.NORTH);

f.add(p2);

p3.add(bt2,BorderLayout.NORTH);

p3.add(bt1);

p1.add(tf);

f.add(p3,BorderLayout.EAST);

String[]b={"1","2","3","+","4","5","6","-","7","8","9","*","0",".","復位","/"};

for(inti=0;i<16;i++)

{

bt[i]=newButton(b[i]);

p2.add(bt[i]);

}

bt[0].setForeground(Color.blue);

bt[1].setForeground(Color.blue);

bt[2].setForeground(Color.blue);

bt[4].setForeground(Color.blue);

bt[5].setForeground(Color.blue);

bt[6].setForeground(Color.blue);

bt[8].setForeground(Color.blue);

bt[9].setForeground(Color.blue);

bt[10].setForeground(Color.blue);

bt[12].setForeground(Color.blue);

bt[13].setForeground(Color.blue);

bt[3].setForeground(Color.red);

bt[7].setForeground(Color.red);

bt[11].setForeground(Color.red);

bt[15].setForeground(Color.red);

bt[14].setForeground(Color.red);

bt1.setForeground(Color.red);

bt2.setForeground(Color.red);

f.pack();

f.setVisible(true);

f.addWindowListener(newWindowAdapter()

{

publicvoidwindowClosing(WindowEvente)

{

System.exit(0);

}

}

);

bt[0].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s+=1;

s2+=1;

tf.setText(s);

}

}

);

bt[1].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s+=2;

s2+=2;

tf.setText(s);

}

}

);

bt[2].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s+=3;

s2+=3;

tf.setText(s);

}

}

);

bt[4].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s+=4;

s2+=4;

tf.setText(s);

}

}

);

bt[5].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s+=5;

s2+=5;

tf.setText(s);

}

}

);

bt[6].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s+=6;

s2+=6;

tf.setText(s);

}

}

);

bt[8].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s+=7;

s2+=7;

tf.setText(s);

}

}

);

bt[9].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s+=8;

s2+=8;

tf.setText(s);

}

}

);

bt[10].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s+=9;

s2+=9;

tf.setText(s);

}

}

);

bt[12].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s+=0;

s2+=0;

tf.setText(s);

}

}

);

bt[13].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s+='.';

s2+='.';

tf.setText(s);

}

}

);

bt[3].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s1=s;

s+='+';

id=1;

s2="";

tf.setText(s);

}

}

);

bt[7].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s1=s;

s+='-';

id=2;

s2="";

tf.setText(s);

}

}

);

bt[11].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s1=s;

s+='*';

id=3;

s2="";

tf.setText(s);

}

}

);

bt[14].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s="";

s2="";

tf.setText(s);

}

}

);

bt[15].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s1=s;

s+='/';

id=4;

s2="";

tf.setText(s);

}

}

);

bt1.addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

if(id<1);

else{

s+='=';

doublea=Double.parseDouble(s1);

doubleb=Double.parseDouble(s2);

doublec=0;

switch(id)

{

case1:c=a+b;break;

case2:c=a-b;break;

case3:c=a*b;break;

case4:c=a/b;break;

}

s+=c;

tf.setText(s);

}

s="";s1="";s2="";id=0;

}

}

);

bt2.addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

char[]c1;

char[]c2=newchar[s.length()-1];

c1=s.toCharArray();

for(inti=0;i<s.length()-1;i++)

c2[i]=c1[i];

s=s.valueOf(c2);

if(id<1)

{

s1=s;

}

if(s2.length()>=1)

{

char[]c3;

char[]c4=newchar[s2.length()-1];

c3=s2.toCharArray();

for(inti=0;i<s2.length()-1;i++)

c4[i]=c3[i];

s2=s2.valueOf(c4);

}

tf.setText(s);

}

}

);

}

}

閱讀全文

與java計算加減乘除相關的資料

熱點內容
漢壽小程序源碼 瀏覽:340
易助erp雲伺服器 瀏覽:530
修改本地賬戶管理員文件夾 瀏覽:416
python爬蟲工程師招聘 瀏覽:283
小鵬p7聽音樂哪個app好 瀏覽:354
linux下的防火牆 瀏覽:954
凌達壓縮機美芝壓縮機 瀏覽:350
php後面代碼不執行 瀏覽:236
微我手機怎樣設置應用加密 瀏覽:202
條件加密 瀏覽:628
androidstudio設置中文 瀏覽:641
汽車換壓縮機能提升製冷 瀏覽:628
安卓開發配什麼電腦 瀏覽:607
linux下php模塊 瀏覽:78
阿里雲伺服器終端在哪裡 瀏覽:148
app紙有什麼用 瀏覽:224
cuteftp命令 瀏覽:507
最開始的編程語言是什麼 瀏覽:760
at遠程命令 瀏覽:493
雲伺服器哪家好點 瀏覽:215