I can make this:
for (int i=0; i<6; i++){
for (int j=0; j<i; j++){
System.out.print("*");
}
System.out.println("");
}
but I cannot find out how to write a static void method that receives a positive integer and uses nested for-loops to display a right triangle made up of integers 1 to the number received
you can create static private method with size parameter and call from main method like below -
public static void main(String[] args) {
makeTriangle(6);
}
private static void makeTriangle(int size){
for (int i=0; i<size; i++){
for (int j=0; j<i; j++){
System.out.print("*");
}
System.out.println("");
}
}
Just define static method like this:
public class Test {
public static void printRightTriangle(int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
System.out.print("*");
}
System.out.println("");
}
}
public static void main(String[] args) {
printRightTriangle(12);
}
}
Hope it can help.
I think you're looking to print a right-angled triangle made up of integers in a method that takes a positive int.
public static void printTriangle(int maxVal) {
for (int i=1; i<=maxVal; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j);
}
System.out.println("");
}
Try this way:
public static void main(String[] args) {
printRightTriangle(6);
}
public static void printRightTriangle(int rows) {
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < i; ++j) {
System.out.print("* ");
}
System.out.println();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.