i'm going through beginners exercise writing small program in java. task print out (i.e. find algorithm) following output
xooooooooo xxoooooooo xxxooooooo xxxxoooooo xxxxxooooo xxxxxxoooo xxxxxxxooo xxxxxxxxoo xxxxxxxxxo xxxxxxxxxx
i have figured out how code wrote seems repetitive , tedious. how can shorten code? there must easier way achieve this?
here code of now;
package helloworld; public class helloworld { public static void main(string[] args) { // output // algorithm 1 boolean ft = true; string s = new string(); for(int = 0; < 10; i++) { s += "x"; for(int j = 0; j < 9; j++) { if(i == 0) { s += "o"; } if(i == 1) { if(ft == true) { s+="x"; ft = false; } if(j == 8) { continue; } s += "o"; } if(i == 2) { if(ft == true) { s+= "xx"; ft = false; } if(j == 7) { break; } s += "o"; } if(i == 3) { if(ft == true) { s+= "xxx"; ft = false; } if(j == 6) { break; } s += "o"; } if( == 4) { if(ft == true) { s+= "xxxx"; ft = false; } if(j == 5) { break; } s += "o"; } if( == 5) { if(ft == true) { s+= "xxxxx"; ft = false; } if(j == 4) { break; } s += "o"; } if( == 6) { if(ft == true) { s+= "xxxxxx"; ft = false; } if(j == 3) { break; } s += "o"; } if( == 7) { if(ft == true) { s+= "xxxxxxx"; ft = false; } if(j == 2) { break; } s += "o"; } if( == 8) { if(ft == true) { s+= "xxxxxxxx"; ft = false; } if(j == 1) { break; } s += "o"; } if( == 9) { if(ft == true) { s+= "xxxxxxxxx"; ft = false; } if(j == 0) { break; } s += "o"; } } system.out.println(s); s = ""; ft = true; } } }
just use 2 nested loops:
string s; for( int = 0; < 10; i++) { s = ""; for( int j = 0; j <= i; j++) s+= "x"; for( int j = i+1; j < 10; j++) s+= "o"; system.out.println(s); }
Comments
Post a Comment