I’m supposed to write a nested for loop that prints the following output:
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
I’m supposed to use two methods.
The main method is only supposed to get the number of rows desired from the user.
I’m supposed to write another method called printPyramid that:
- Has the number of rows
- Prints a pyramid with that number of rows
- Returns nothing.
So far, I have:
import java.util.Scanner;
public class Pyramid {
//Getting number of rows, calling printPyramid in main method
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Get user input = number of lines to print in a pyramid
System.out.println("Enter the number of lines to produce: ");
int numLines = input.nextInt();
//call method:
printPyramid();
}//End of main method
//Making a new method...
public static void printPyramid (int numLines) {
int row;
int col;
row = 0;
col = 0;
for (row = 1; row <= numLines; row++){
//print out n-row # of spaces
for (col = 1; col <= numLines-row; col++){
System.out.print(" ");
}
//print out digits = 2*row-1 # of digits printed
for (int dig= 1; dig <= 2*row-1; dig++){
System.out.print(row + " ");
}
System.out.println();
}//end of main for loop
}//end of printPyramid
}//end of class
I get errors and I can’t figure out how to get it to print out correctly.
I believe the methods are messed up?
Two big errors here. Firstly, ALL with Java are classes so you have to put that main method inside a class. For example:
Second one, you have to call the method
printPyramidinside the main, because it will not be executed if isn’t called first.I hope this small indications help you.