java - How to add a String with a loop -
update 3: solved, thank you
update 2: ok close isn't printing tails
update dont want use stringbuilder havn't learned concept. cannot figure out wrong , how add 1 r
hello trying figure out how assignment asked int user input , generate number of coin flips in string form resulting in pattern of hhththttthhhh etc depending on input user chose.
final update solved:
public class stringaddition{ public static void main(string[] args) { system.out.println(coinflip(8)); } public static string coinflip(int a){ string r =""; for(int = 0; < a; i++){ int coin = (int) (math.random() * 2); if (coin == 0) { string 1 = "t"; r+=one; } else if (coin == 1){ string 1 = "h"; r +=one; } } return r; } }
you have declare empty string outside of loop, , add inside loop. +=
less efficient stringbuilder, here solution
public static string coinflip(int a){ stringbuilder sb = new stringbuilder(); for(int = 0; < a; i++){ int coin = (int)(math.random() * 2); sb.append(coin == 0 ? "t" : "h"); // if-else } return sb.tostring(); }
Comments
Post a Comment