loops - Java StringBuilder how to not print "to" at the end -
loops - Java StringBuilder how to not print "to" at the end -
my stringbuilder travelroute printing "destination1 destination2 destination 3 to", how can avoid getting "to" @ end of string?
arraylist<string> itinerary = new arraylist<string>(); scanner kb = new scanner(system.in); string userchoice; string uppercase;  while (true) {     system.out.print("destination: ");     userchoice = kb.next();     uppercase = userchoice.touppercase();     if (uppercase.equals("done")) {         break;     } else         itinerary.add(userchoice);  }  stringbuilder travelroute = new stringbuilder(); (int count = 0; count < itinerary.size(); count++) {     string uppercasedestination = itinerary.get(count).touppercase();     travelroute.append(uppercasedestination + " to"); }  system.out.println(travelroute);       
two ways solve mutual problem:
add"to" in front of terms, except first add after every term, clean after loop   code 1:
stringbuilder travelroute = new stringbuilder();  for(int count = 0; count < itinerary.size() ; count++) {     if (count > 0) {         travelroute.append(" ");      }     string uppercasedestination = itinerary.get(count).touppercase();     travelroute.append(uppercasedestination);  }    code 2:
// after loop travelroute.setlength(travelroute.length() - 3);    personally, prefer alternative 1.
 java loops concatenation stringbuilder 
 
Comments
Post a Comment