我正在编写一个代码来重塑信号。我正在通过不必要的重复获得输出。
INPUT:
String [] rani = {“A”,“1”,“2”,“OK”,“B”,“3”,“4”,“OK”,“B”,“1”,“ 3" , “OK”};
必需的输出:
A / 3 B / 7 B / 4
获得了输出:
A / 3 A / 3 A / 3 A / 3 B / 7 B / 7 B / 7 B / 7 B / 4
算法:单字母串(“A”,“B”等)后跟数字串(“1”,“2”等)。每个字母表字符串后跟斜杠和数字的总和,字符串“OK”将被忽略。
作为java和编程的新手我需要帮助来获得所需的输出。
我的代码是:
public class SignalOK {
public static void main(String[] arg) {
String finalSignal = "";
String netSignal = "";
String name = "";
int total = 0;
String[] rani = { "A", "1", "2", "OK", "B", "3", "4", "OK", "B", "1",
"3", "OK" };
for (int i = 0; i < rani.length; i++) {
if ((rani[i] == "A") || (rani[i] == "B")) {
name = rani[i];
}
if ((rani[i] == "1") || (rani[i] == "2") || (rani[i] == "3")
|| (rani[i] == "4")) {
total = total + Integer.valueOf(rani[i]);
}
if (rani[i] == "OK") {
netSignal = name + "/" + String.valueOf(total) + " ";
name = "";
total = 0;
}
finalSignal = finalSignal + netSignal;
}
System.out.println(finalSignal);
}
}
答案 0 :(得分:6)
如果括号:
,只需在"OK"
内移动最终结果字符串连接
if (rani[i].equals("OK")) {
netSignal = name + "/" + String.valueOf(total) + " ";
name = "";
total = 0;
finalSignal = finalSignal + netSignal;
}
另外,请始终使用.equals()
来比较字符串。
答案 1 :(得分:1)
另一种方法: -
public static void main(String[] args) {
String[] inputString = {"A","1","2","OK","B","3","4","OK","B","1","3","OK"};
StringBuilder sb = new StringBuilder();
for(String s : inputString)
sb.append(s); // creating a String from array contents
String ss[] = sb.toString().split("OK"); // split on the basis of 'OK'
sb.setLength(0); // emptying the sb, so that it can be used later on also
for(String s : ss){
char[] ch = s.toCharArray();
sb.append(ch[0]); // first alphabet like 'A','B','C'
int val = 0;
for(int i = 1; i< ch.length ; i++)
val +=Integer.parseInt(""+ch[i]); // calculate the int value
sb.append("/"+val+" "); // finally appending alphabet with int value
}
System.out.println(sb);
}
输出: - A/3 B/7 B/4