JAVA初学者简单编写四则混合运算

Java初学者简单编程运算法;只使用for循环与数组;重点在于String的API使用。

public class 四则运算 {

public static void main(String[] args) {
Scanner str1 = new Scanner(System.in);
System.out.println("请输入:");
String str = str1.nextLine();
String strs = str.replace("+","-");
String[] s = strs.split("-");
double temp=0;
double sum=0;
//遍历截取了的字符数组
for(String a:s){
//查找有*或/的数组
if(a.contains("*")||a.contains("/")){
//遍历带符号的数组
for(int i=0;i<a.length();){
//设置一个变量,来控制下标,
int count = 1;
//需要截取的字符串长度
a:for(int j=i+1;j<a.length();j++){
//取出下一个字符
char c = a.charAt(j);
// System.out.println(c+"===");
//如果字符是*或/
if(c=='*'||c=='/'){
//终止a循环
break a;
}else{
//如果不是就长度加一;
count++;
}
}
//截取字符串
String strNun =a.substring(i,i+count);
// System.out.println(strNun+"=========");
//转变为数字
double d = Double.parseDouble(strNun);
//第一个数字
if(i==0){
temp = d;
}else{
//取出当前的数字前面的符号
char t =a.charAt(i-1);
//如果运算符是*
if(t=='*'){
//前一个数就乘它
temp*=d;
}else if(t=='/'){
temp/=d;
}
}
//把坐标向后移一个长度
i+=count+1;
}
str = str.replace(a, temp+"");
}
}
//计算加减,与上面的思路一样
for(int i = 0;i<str.length();){
int count =1;
a:for(int j=i+1;j<str.length();j++){
char c = str.charAt(j);
if(c=='+'||c=='-'){
break a;
}else{
count++;
}
}
String strNum = str.substring(i,i+count);
double d  =Double.parseDouble(strNum);
if(i==0){
sum=d;
}else {
char s2 =str.charAt(i-1);
if(s2=='+'){
sum+=d;
}else if(s2=='-'){
sum-=d;
}
}
i+=count+1;
}
System.out.println(sum);
}
}
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值