本文目录一览:
JAVA中如何解析字符串公式,并且利用公式进行计算
可以使用 commons-jexl3 jar包
示例:
public static void main(String[] args){
String expressionString = "1+2+3";
JexlEngine jexlEngine = new JexlBuilder().create();
JexlExpression jexlExpression = jexlEngine.createExpression(expressionString);
Object evaluate = jexlExpression.evaluate(null);
System.out.println(evaluate);
}
结果: 6
示例2:
来个复杂点的
public static void main(String[] args){
// String expressionString = "1+2+3";
String expressionString = "100*10-(200+300)";
JexlEngine jexlEngine = new JexlBuilder().create();
JexlExpression jexlExpression = jexlEngine.createExpression(expressionString);
Object evaluate = jexlExpression.evaluate(null);
System.out.println(evaluate);
}
结果: 500
java 解析-字符串
import java.text.DecimalFormat;
public class StrTest {
public static String[] SpiltString(String str){
char[] allChars = str.toCharArray();
for(int i = 0 ; iallChars.length ; i++){
if(!( (allChars[i]='0' allChars[i]='9') || allChars[i]=='-' || allChars[i]==',') ){
System.out.println("ERROR");
throw new RuntimeException();
}
}
StringBuffer strArray = new StringBuffer();
String[] firstStr = str.split(",");
for(int i = 0 ; ifirstStr.length ; i++){
if(firstStr[i].indexOf("-") == -1){
strArray.append(firstStr[i]+" ");
}else{
String[] secondStr = firstStr[i].split("-");
try{
int min =Integer.valueOf( secondStr[0] );
int max =Integer.valueOf( secondStr[secondStr.length-1] );
int len = secondStr[0].length();
String newStr = null;
String formatStr = "00000000000000000000000000000000";
for(int j = min;j=max;j++){
DecimalFormat df = new DecimalFormat(formatStr.substring(0,len));
newStr =df.format(j);
strArray.append(newStr+" ");
}
}catch(NumberFormatException e){
continue;
}
}
}
return strArray.toString().split(" ");
}
public static void main(String[] args) {
String [] str = SpiltString("001,002-005,007");
for(int i = 0 ; i str.length;i++){
System.out.print(str[i]+" ");
}
}
}
java解析json字符串 放到数组中
java解析json字符串时将大括号中的对应为一个类,里面的数据对应为类的属性,最后用数组接受即可。
示例关键代码如下:
//导入 net.sf.json.JSONArray和net.sf.json.JSONObject 两个jar 包
String str = "[{name:'a',value:'aa'},{name:'b',value:'bb'},{name:'c',value:'cc'},{name:'d',value:'dd'}]" ; // 一个未转化的字符串
JSONArray json = JSONArray.fromObject(str ); // 首先把字符串转成 JSONArray 对象
if(json.size()0){
for(int i=0;ijson.size();i++){
JSONObject job = json.getJSONObject(i); // 遍历 jsonarray 数组,把每一个对象转成 json 对象
System.out.println(job.get("name")+"=") ; // 得到 每个对象中的属性值
}
}