public class printing { public static void printstars(int amount) { int = 1; while (i<amount) { system.out.print("*"); i++; if (i==amount) { system.out.println("*"); } } } public static void printtriangle(int size) { int c = 1; while (c<=size) { printstars(c); c++; } } public static void main(string[] args) { printstars(3); system.out.println("\n---"); printsquare(4); system.out.println("\n---"); printrectangle(5, 6); system.out.println("\n---"); printtriangle(3); system.out.println("\n---"); }
}
i'm following online course on learning java , in assignment, printtriangle(3) should print 3 rows of stars, first row 1 star, second row 2 stars, third row 3 stars.
i can't figure out why prints 2 rows of stars, first row 2 stars , second row 3 stars.
i edited out parts defined methods printsquare , printrectangle because figured weren't important.
the program i'm using code netbeans tmc 1.1.7
get rid of if loop
, change condition in while loop
i<=amount
. what's happening in while loop is, checking if i
less amount
( < amount )
. in first iteration call printstars(1) in case amount = 1
, i = 1
. in while loop comparison becomes 1<1
false
. if condition
(i==amount)
not reached because outer while loop broke, method execution ends without printing 1 star expected. if change while condition i<=amount
comparison 1<=1
condition true
print 1 star.
public static void printstars(int amount) { int = 1; while (i<=amount) { system.out.print("*"); i++; } system.out.println(""); }
Comments
Post a Comment