加減乘除java
1、打開eclipse,創建一個Java工程,在此工程里新建一個類;
2、在新建的類中,添加4個運算類;
3、在主方法中調用對應的方法即可完成分數的加減乘除運算了。
具體實現代碼如下:
public class Demo {
public static void main(String[] args) {
System.out.println(jia(1, 2));
System.out.println(jian(1, 2));
System.out.println(cheng(1, 2));
System.out.println(chu(1, 2));
}
//加法運算
private static float jia(float x,float y) {
return x + y;
}
//減法運算
private static float jian(float x,float y) {
return x - y;
}
//乘法運算
private static float cheng(float x,float y) {
return x * y;
}
//除法運算
private static float chu(float x,float y) {
return x / y;
}
}
『貳』 用java怎樣編寫加減乘除,從鍵盤輸入,例如:1+2按回車之後可以運算,小數整數都可以
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
System.out.println("請輸入第一個數:");
double n1 = sc.nextDouble();
System.out.println("請輸入運算符:");
String s = sc.next();
System.out.println("請輸入第二個數:");
double n2 = sc.nextDouble();
if(s.equals("+")){
System.out.print(n1+"+"+n2+" = "+(n1+n2));
}else if(s.equals("-")){
System.out.print(n1+"+"+n2+" = "+(n1-n2));
}else if(s.equals("*")){
System.out.print(n1+"*"+n2+" = "+(n1*n2));
}else if(s.equals("/")){
if(n2==0){
System.out.println("除數不能等於0");
}else{
System.out.print(n1+"/"+n2+" = "+(n1/n2));
}
}else{
System.out.println("運算符輸入錯誤,請重新輸入。");
}
}