您的位置:首页 > 编程语言 > Java开发

Java中命令行执行四则运算的功能

2016-12-14 17:06 302 查看
代码如下:
package math;

public class Algorithm {

/**
* @param args
*/
public static void main(String[] args) {
String s=args[0];
if(s.indexOf("+")>-1){
String[] str=s.split("[+]");
if(str[0].matches("[0-9]+")&&str[1].matches("[0-9]+")){
System.out.println(Double.parseDouble(str[0])+Double.parseDouble(str[1]));
}
else{
System.out.println("操作数非数字");
}
}else if(s.indexOf("-")>-1){
String[] str=s.split("[-]");
if(str[0].matches("[0-9]+")&&str[1].matches("[0-9]+")){
System.out.println(Double.parseDouble(str[0])-Double.parseDouble(str[1]));
}
else{
System.out.println("操作数非数字");
}
}else if(s.indexOf("*")>-1){
String[] str=s.split("[*]");
if(str[0].matches("[0-9]+")&&str[1].matches("[0-9]+")){
System.out.println(Double.parseDouble(str[0])*Double.parseDouble(str[1]));
}
else{
System.out.println("操作数非数字");
}
}else if(s.indexOf("/")>-1){
String[] str=s.split("[/]");
if(str[0].matches("[0-9]+")&&str[1].matches("[0-9]+")){
System.out.println(Double.parseDouble(str[0])/Double.parseDouble(str[1]));
}
else{
System.out.println("操作数非数字");
}
}else {
System.out.println("运算符非四则运算符(+,-,*,/)");
}
}

}
以上代码可能存在一些冗余的部分,没有进行修改,如果需要可以自行拷贝和修改。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息