java 从左往右遍历,计算算式的值
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 从左往右遍历,计算算式的值相关的知识,希望对你有一定的参考价值。
package com.example.a24107.computeapplication2;
/**
* Created by 24107 on 2017/12/8.
*/
public class StrToNum {
/**
* 从左往右遍历,先把括号找出来,再计算括号中的值,去掉括号,再计算*和/,再计算+和-,
*/
public static void main(String[] args){
float answer = LeftToRightCompute("2+2×5.5-2");
System.out.println(answer);
}
public static float LeftToRightCompute(String str) {
int numcount = -1;
float firstnum = 1;
float answer = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) >= '0' && str.charAt(i) <= '9') {
if (numcount==-1) {
numcount = i;
}
firstnum = Float.parseFloat(str.substring(numcount, i+1));
answer = firstnum;
//return answer;
}
else {
switch (str.charAt(i)) {
case '+':
numcount = -1;
answer=firstnum + LeftToRightCompute(str.substring(i + 1));
return answer;
//break;
case '-':
numcount = -1;
answer=firstnum - LeftToRightCompute(str.substring(i + 1));
return answer;
//break;
case '×':
numcount = -1;
float secondnummulti = FirstnumLeftToRight(str.substring(i+1));
float answer1 = firstnum * secondnummulti;
String newstringmuti;
if (secondnummulti==(int)secondnummulti) {
newstringmuti = str.substring(i + 1 + Float.toString(secondnummulti).length()-2);
}
else{
newstringmuti = str.substring(i + 1 + Float.toString(secondnummulti).length());
}
newstringmuti = answer1+ newstringmuti;
answer = LeftToRightCompute(newstringmuti);
return answer;
//break;
case '÷':
numcount = -1;
float secondnumchu = FirstnumLeftToRight(str.substring(i+1));
float answer2 = firstnum*secondnumchu;
String newstringchu = answer2+str.substring(i+1+Float.toString(answer2).length());
answer = LeftToRightCompute(newstringchu);
return answer;
//break;
case '(':
numcount = -1;
float answer3 = LeftToRightCompute(str.substring(i+1));
break;
case ')':
numcount = -1;
return answer;
//break;
}
}
}
return answer;
}
public static float FirstnumLeftToRight(String str) {
int numcount = -1;
float firstnum = 0;
if (str.charAt(0)=='('){
return LeftToRightCompute(str.substring(1));
}
else {
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) >= '0' && str.charAt(i) <= '9'||str.charAt(i)=='.') {
if (numcount==-1) {
numcount = i;
}
firstnum = Float.parseFloat(str.substring(numcount, i + 1));
}
else {
return firstnum;
}
}
}
return firstnum;
}
}
以上是关于java 从左往右遍历,计算算式的值的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode练习(Python):栈类:第103题:二叉树的锯齿形层次遍历:给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
2021-10-06:二叉树的锯齿形层序遍历。给定一个二叉树,返回其节点值的锯齿形层序遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。力扣103。