2014-06-09 43 views
2

操作包含数学操作数的Java字符串。操作包含数学操作数的Java字符串

我正在修改控制信号的代码。我有这种字符串转换:

String str= "Red 0.20 + 0.60 Green 0.30 + 0.45 + 0.56 Blue 0.25 + 0.50 + 1.0 Yellow 3.0/2.0 "; 

这样:

String str1= "RedNet0.8 GreenNet0.75 BlueNet1.75 YellowNet1.5 "; 

我可以代替红到红网,绿能格林耐特等,但帮助我继续进行剩余部分。

+0

'的String [] = STR1 str.split(”“)'后,你知道,在某些位置,你有运营商,在别人的价值观等等。遍历数组str1并解析所有的数据。 – Nicola

回答

-1
StringTokenizer st = new StringTokenizer(msg,"+"); while(st.hasMoreTokens()){ System.out.println(st.nextToken()); 

0

伪的解决方案:

String[] tokens = input.split(" "); 
int index = 0; 

while(index < tokens.length) { 
    String colorName = tokens[index++]; 
    Decimal colorValue = parseNumber(tokens[index++]); // Use some appropriate decimal datatype here 

    while(true) { 
     String operator = tokens[index]; 
     if (operator is neither "+", "-" nor any of the other operators) { 
      break; 
     } 
     index++; 
     switch(tokens[index++]) { 
      case "+": 
       colorValue += parseNumber(tokens[index++]); 
       break; 
      case "-": 
       colorValue -= parseNumber(tokens[index++]); 
       break; 
      ... and so on for all operators ... 
     } 
    } 

    output colorName + "Net" + colorValue + " "; 
}