java - Building a pyramid and outputting the first line -
based on code below trying print out pyramid using input of rows looks this:
* *o* *o*o*
but arbitrary amount of rows. lines correctly cant figure out how first star correctly line up. outputs rows being 5:
* *o* *o *o *o* *o *o *o *o *o* *o *o *o *o *o *o *o* *o *o *o *o *o *o *o *o *o*
my code :
system.out.println("please enter number of rows: "); int row = scan.nextint();//takes in number of rows in=scan.nextline(); //gets rid of error .nextint(); string s="*"; string pat="o"; if(row>1){//this run through if number of rows entered greater 1 (int =0; <= row; i++) {//this loop used build pyramid pattern // spacing (int j = 1; j <= row - i; j++){ system.out.print(" "); } // left half of pyramid (int k = i; k >= 1; k--){ if(k==0){ system.out.println(s); }else{ system.out.print((k >= row+1) ? + k: " "+s + pat); } } // corresponding right half of pyramid (int k = 2; k <= i; k++) { system.out.print((k >= row+1) ? +k : " "+ s + pat); } // next line system.out.println("*"); } }else{ system.out.println(s); }
what row? it's 0 or more spaces followed *
followed n
repeats of o*
n
=0,1,2,... advance next line.
translate java, ignoring spaces now:
static void printrowvisiblepart(int n) { system.out.print("*"); (int = 0; < n; i++) { system.out.print("o*"); } system.out.println(); }
just fun, let's use print out visible part of pyramid of height k
:
public class pyramidprinter { public static void main(string[] args) { int k = integer.parseint(args[0]); (int n = 0; n < k; n++) { printrowvisiblepart(n); } } private static void printrowvisiblepart(int n) { system.out.print("*"); (int = 0; < n; i++) { system.out.print("o*"); } system.out.println(); } }
we get:
* *o* *o*o* *o*o*o* *o*o*o*o*
this close. need spaces @ start of each line.
how many? start writing little method print them:
static void printspaces(int n) { (int = 0; < n; i++) { system.out.print(' '); } }
there fancier ways, fine.
now work backward. last row have n
= k-1
k
read user. know in row need 0 spaces. inspecting picture, note each row has 1 more space successor. row zero, then, need k-1
spaces, counting down each successive row 0 @ row k-1
. in row n
, need k - 1 - n
spaces. change main
bit print these spaces before each visible part of line.
public static void main(string[] args) { int k = integer.parseint(args[0]); (int n = 0; n < k; n++) { printspaces(k - 1 - n); // k-1 @ n=0 , 0 @ n=k-1! printrowvisiblepart(n); } }
Comments
Post a Comment