加减乘除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("运算符输入错误,请重新输入。");
}
}