Reputation: 131
I am writing a code to reshape the signals. I am getting the output with unwanted repetitions.
INPUT:
String[] rani = {"A","1","2","OK","B","3","4","OK","B","1","3","OK"};
Required OUTPUT:
A/3 B/7 B/4
Got OUTPUT:
A/3 A/3 A/3 A/3 B/7 B/7 B/7 B/7 B/4
ALGORITHM: Single alphabet strings ("A","B" etc.) are followed by number strings ("1","2" etc.). Each alphabet string is to be followed by slash and total of the numbers, and string "OK" is to ignored.
Being newcomer to java and programming I need help to get the needed output.
My code is:
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);
}
}
Upvotes: 2
Views: 68
Reputation: 2820
A different approach :-
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);
}
Output :- A/3 B/7 B/4
Upvotes: 1
Reputation: 46209
Just move the final result string concatenation inside the "OK"
if brackets:
if (rani[i].equals("OK")) {
netSignal = name + "/" + String.valueOf(total) + " ";
name = "";
total = 0;
finalSignal = finalSignal + netSignal;
}
Also, always use .equals()
to compare strings.
Upvotes: 6