arrays - Output goes stray at START and at END of a java loop -
i writing code translating signals 1 form form. code works fails ends.
input: string [] test = {"b","100","b","b","2","3","100","b","200","b","3","17","b","10" };
required output: b/101 b/1 b/106 b/201 b/21 b/11
got output: b/1 b/101 b/1 b/106 b/201 b/21
comparison of required output , got output
first term b/1 not required in got output. b/11 missing @ end in required output.
algorithm: "b" replaced "b/", , followed addition of numbers appearing in strings "2", "3","100" gives 105 , "1" added "b" hence 106 , final result becomes 'b/106'.
i new comer java , programming. need required output.
this code:
public class signalconversion { public static void main(string args[]) { string [] test ={"b","100","b","b","2","3","100","b","200","b","3","17","b","10" }; int i=0; int x=test.length; string netsignal=""; int total=0; while(!(x==0)){ stringbuilder sb_matra= new stringbuilder(); stringbuilder sb_sur= new stringbuilder(); if(!test[i].equals("b")) { total=total+(integer.valueof(test[i])); } else { total=total+1; sb_sur.append(test[i]+"/"+integer.tostring(total)+" " ); total=0; } netsignal=sb_sur.tostring()+sb_matra.tostring(); system.out.printf(netsignal); i++; x--; } } }
when encounter "b", should start summing numbers following it, output result when encounter next "b". that's why have problem @ ends. print first "b" when encounter it, before calculating number should come it.
similarly, @ end of loop, should add additional b last sum.
here's potential way of doing (i think loop simpler yours):
stringbuilder sb_sur= new stringbuilder(); boolean first = true; (int = 0; < test.length; i++) { if(!test[i].equals("b")) { total=total+(integer.valueof(test[i])); } else { if (!first) { total=total+1; sb_sur.append("b/"+integer.tostring(total)+" " ); total=0; } first = false; } } total=total+1; // account last b sb_sur.append("b/"+integer.tostring(total)+" " );
Comments
Post a Comment