Printing pyramid in Java on the console - java

How can I print a pyramid in Java like this
1
23
456
78910
My current code looks like this:
public class T {
public static void main(String[] args) {
int i, j, num = 1;
int n = Integer.parseInt(args[0]);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.println(num);
num++;
}
System.out.println(" ");
}
}
}
If I try this removing declared i & j then it shows an array out of bounds exception
However 'i' & 'j' are creating the problem. What should my code look like.

int val=1;
for(int i=0;i<6;i++){
for(int j=1;j<i;j++){
System.out.print(val);
val++;
}
System.out.print("\n");
}
initially val is equal to 1 . Inside the first for loop i=0 and j with increase from 1, but when i=0 second for loop doesn't run. then you get the first value as 1. Then it will point to new line.
When i=1,j still 1 so second for loop runs 1 time and print 2, because val has increment(val++). when j=2 in inside for loop it is not running only print the new value (3) of val there.
so on this will work

public static void main(String[] args) {
int num = 1;
//i is how many numbers per row
for(int i = 1; i < 5; i++){
//prints i numbers because j increases from 0 to i, incrementing num each time
for(int j = 0; j < i; j++){
System.out.print(num++);
}
System.out.println();
}
}
This code will work for your purposes.
Now, please read on if you would like to understand Java better and see why the compiler was throwing errors in your code. You shouldn't use stackoverflow to copy in paste someone else's code without understanding it. In your code, you were declaringi and j twice. In Java, you cannot declare a variable twice. You did it first in int i,j, num = 1; and then again in each for loop for (int i = 1; i <= lines; i++). You could correct this by saying for(i = 1; i <= lines; i++). Notice how the int is left out in the second version of the for loop. You can simply assign a value to a variable in a for loop rather than creating a new variable as you do when declare the type int i = 1
The syntax of a for loop is:
for(initialization; Boolean_expression; update)
{
//Statements
}
The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
As for the array out of bounds error that you receive, you are trying to read in a command line argument in the statement int n = Integer.parseInt(args[0]); Notice how the main method has a parameter String[] args. These are called command line arguments and can be passed in if you manually run the program from the command line. You were trying to read in args[0] which is outside of the bounds of args[].
In other words, if you run
java MyProgram one two
Then args contains:
[ "one", "two" ]
public static void main(String [] args) {
String one = args[0]; //=="one"
String two = args[1]; //=="two"
}

I suppose you give the number of lines as your only argument, so the code would be
public static void main(String[] args)
{
int lines = Integer.parseInt(args[0]);
int num = 1;
for (int i = 1; i <= lines; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(num);
num++;
}
System.out.println("");
}
}

int l=1;
for (int i=0; i<5; i++)
{
for (int k=0; k<5-i; k++)
{
System.out.print(" ");
}
for (int j=0; j<(i*2)+1; j++)
{
if(j%2!=0){
System.out.print(l++);
}else {
System.out.print(" ");
}
}
System.out.println("");
}

public static void pyramid(int max) {
int num = 1;
max = 4;
for (int row = 0; row < max; row++) {
for (int column = 0; column < max; column++)
System.out.print(column <= row ? num++ : " ");
System.out.println();
}
}

import java.util.Scanner;
/**
*
* #author shelc
*/
public class PrintNumberPyramid {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the count : ");
int number = scanner.nextInt();
//enter the number of rows you want to print
pyramid(number);
}
public static void pyramid(int rows) {
int count = 1;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < rows; j++) {
System.out.print(j <= i ? count++ : " ");
}
System.out.println();
}
}
}

Related

create two dimensional array that can store integer values inside, and square them in different method and print them in another method

Complete question is: Create a program that uses a two dimensional array that can store integer values inside. (Just create an array with your own defined rows and columns). Make a method called Square, which gets each of the value inside the array and squares it. Make another method called ShowNumbers which shows the squared numbers.
What I attempted thou it has errors:
public class SquareMatrix {
public static void main(String[] args) {
int sqr[][]= {{1,3,5},{2,4,6}};
System.out.println("Your Original Matrix: ");
for(int i = 0; i < 2; i++){
for(int j = 0; j < 3; j++){
System.out.print(sqr[i][j] + " ");
}
System.out.println();
}
Square();
ShowNumbers();
}
static void Square(){
for(int i = 0; i <= 1; i++) {
for(int j = 0; j <= 2; j++) {
sqr[i][j] = sqr[i][j] * sqr[i][j];
}
}
}
static void ShowNumbers(){
System.out.println("Matrix after changes: ");
for(int i = 0; i < 2; i++){
for(int j = 0; j < 3; j++){
System.out.print(sqr[i][j] + " ");
}
System.out.println();
}
}
}
Also how would I write it if I wanted an input from the user for the col and row for a specific range of 0 to 10, I made an alternative version with many errors below. Below code is not as important as the one above
import java.util.Scanner;
public class MyClass {
public static void main(String args[]) {
int row, col, i, j;
int arr[][] = new int[10][10];
Scanner scan = new Scanner(System.in);
try{
System.out.print("Enter Number of Row for Array (max 10) : ");
row = scan.nextInt();
System.out.print("Enter Number of Column for Array (max 10) : ");
col = scan.nextInt();
if(0>=row && row<=10 || 0>=col && col<=10 ){
}
}
catch (Exception e){
System.out.println("(!) Wrong input...\n");
}
System.out.print("Enter " +(row*col)+ " Array Elements : ");
for(i=0; i<row; i++){
for(j=0; j<col; j++){
arr[i][j] = scan.nextInt();
}
}
}
static void square(){
arr[row][col] = arr[row][col] * arr[row][col];
}
static void ShowNumbers(){
System.out.print("The Array is :\n");
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
System.out.print(arr[i][j]+ " ");
}
System.out.println();
}}}
PS I am new to java and would appreciate a response with the whole code pasted not just a section of the code so I don't get lost or with the number of the line the error is from.
thanks for any help
Since you are starting from scratch, it would be good to go over the basics of the language again. Take a look at oracle classvars For your upper problem you need to understand the difference between local and instance variables and the difference between static and non static variables respectively. To solve your issue just move the declaration of your array out of the main method and add a static modifier:
public class SquareMatrix {
static int sqr[][] = {{1, 3, 5}, {2, 4, 6}};
public static void main(String[] args) {
//rest of your code
}

JAVA Need help involving matrices and arrays

I'm working on a test prep program. Its not homework or for a grade, I just need help finishing and fixing it so I can study and better understand how it works. The directions are "Write a program named Matrix1.java that randonly fills in 0s and 1s into an n-by-n matrix, prints the matrix." I'm still pretty new to coding so any help would be greatly appreciated. This is the code I have so far:
public class Matrix1{
public static void main(String[] args){
Matrix1 matrix=new Matrix1(5);
matrix.fill();
matrix.print();
}
public Matrix1(int n){
int[][] matrix = new int[n][n];
}
public void fill(int n){ // randomly fill in 0s and 1s
Random rand = new Random();
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
Integer r = rand.nextInt;
matrix[i][j] = Math.abs(r);
}
}
}
public void print(int[][]matrix, int n){ //print the matrix, each row is printed in a separate line
for(int i = 0; i< n; i++){
for(int j = 0; j<n; j++){
System.out.println(array[i][j]);
}
}
}
}
I ended up confusing myself and I'm not sure how to fix it or continue. I think I'm partially on the right track though.
Your code after fixes.
import java.util.Random;
public class Matrix1 {
private final int[][] matrix;
private final int n;
public Matrix1(int n) {
this.n = n;
this.matrix = new int[n][n];
}
/**
* randomly fill in 0s and 1s
*/
public void fill() {
Random rand = new Random();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = rand.nextInt(2);
}
}
}
/**
* print the matrix, each row is printed in a separate line
*/
public void print() {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(matrix[i][j]);
}
System.out.println();
}
}
public static void main(String[] args) {
Matrix1 matrix = new Matrix1(5);
matrix.fill();
matrix.print();
}
}
So changes I've made:
I've changed "matrix" and "n" variables into class fields, so you don't have to pass them through class methods
filling array - it should be just 0/1 not any integer so you can use rand.nextInt(2) with bounds - it gives values less then 2
printing array - you have to print row in one line, then change line
It looks like the right direction, check your main method to set the necessary parameters (size, array and size).
Also set the Random object to only be 0 or 1 (Check the Java class libraries for the answer) I believe you can set a parameter inside the Random.nextInt method.
Also if its required to print it like a double array, change up your printing logic since you are always writing to a new line
Well, I see a few problems, which if fixed might help get you on the right track.
First of all, for the random integer, you'll probably want to use the method from this answer:
import java.util.concurrent.ThreadLocalRandom;
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
ThreadLocalRandom.current().nextInt(min, max + 1);
I don't think you need to use Math.abs in this case, as long as you call ThreadLocalRandom.current().nextInt(0, 2).
Second, there are a couple of problems with your printing code. First of all, you should be using matrix[i][j] instead of array[i][j]. Second, you'll want to use System.out.print instead of System.out.println.
It should be something like this:
for(int i = 0; i< n; i++){
for(int j = 0; j<n; j++){
System.out.print(matrix[i][j]);
}
System.out.println();
}
public class Matrix1{
public static void main(String[] args){
Matrix1 matrix = new Matrix1(5);
matrix.fill();
matrix.print();
}
private int[][] m; //it is easier use a global variable
public Matrix1(int n){
m = new int[n][n];
}
public void fill(){ // randomly fill in 0s and 1s
for(int i = 0; i < m.length; i++){
for(int j = 0; j < m.length; j++){
if (Math.random() > 0.5) {
m[i][j] = 1;
} else {
m[i][j] = 0;
}
}
}
}
public void print(){ //print the matrix, each row is printed in a separate line
for(int i = 0; i< m.length; i++){
for(int j = 0; j<m.length; j++){
System.out.print(m[i][j]); //only use print() for the same row
}
System.out.println("");
}
}
}

2D array populating not working

I'm trying to populate a 2D array with char's from a string I've read in. I'm having a problem with actually populating this 2D array. It keeps printing a 2D array bigger than what I've given it, and the number always seems to be 6 rather than the letters from the string.
I store the string in an ArrayList called tempArray.
Input strings:
WUBDLAIUWBD
LUBELUFBSLI
SLUEFLISUEB
I instantiate a 2D array with columnlength = 11, and rowcount 3
epidemicArray = new int[rowCount][columnCount];
Array before I try to populate it:
00000000000
00000000000
00000000000
My code:
public static void updateArray(){
//extract string from temp
for (int i = 0; i < tempArray.size(); i++){
String temp = tempArray.get(i);
char[] charz = temp.toCharArray();
for (int j = 0; j < charz.length; j++){
for (int k = 0; k < rowCount; k++){
for (int l = 0; l < columnCount; l++){
epidemicArray[k][l] = charz[j];
}
}
}
}
}
Output: Which I didn't expect
6666666666666666666666
6666666666666666666666
6666666666666666666666
Expected output: (2D array)
WUBDLAIUWBD
LUBELUFBSLI
SLUEFLISUEB
Thanks, this is really bugging me.
Change your code to this:
public static void updateArray(){
//extract string from temp
for (int i = 0; i < tempArray.size(); i++){
String temp = tempArray.get(i);
char[] charz = temp.toCharArray();
for (int j = 0; j < charz.length; j++){
epidemicArray[i][j] = charz[j];
}
}
}
This edit should work since the number of columns is the length of one of the string (same length for the 3 of them).
Here is my output
[EDIT]. #magna_nz, I used the following methods to print the array
public static void printRow(int rowNumber) {
for (int i = 0; i < 11; i++) {
System.out.print( epidemicArray[rowNumber][i] + " ");
}
System.out.println();
}
public static void main(String[] args) {
updateArray();
for (int i = 0; i < 3; i++) {
printRow(i);
}
}
This will print the numbers, but if you want to print characters you can change the above printRow method to something like:
public static void printRow(int rowNumber) {
for (int i = 0; i < 11; i++) {
System.out.print( (char)epidemicArray[rowNumber][i] + " ");
}
System.out.println();
}
And this will give you the following result:
You're overwriting your entire epidemicArray with the last value that charz[j] gets. Which is apparently 66. Actually you're overwriting that entire array with every value from charz and the last one won.

For loop inside for loops java

I am trying to get a for loop inside a for loop so that the output is like this:
I wan the output to show a square
I'm not sure why it isn't doing it.
Below is my code:
import java.util.*;
public class test {
public static void main(String[] args) {
System.out.println("Give me a number : ");
Scanner kb = new Scanner(System.in);
int i = kb.nextInt();
for(int i2=i;i2<i+i;i2++) {
System.out.print("x");
for( i2=i;i2<i+i;i2++) {
System.out.println("x");
}
}
}
}
You need to have separate variables for each of the loops. Otherwise, you'll never run the second iteration of the outer loop. When you're done the inside, your i2 is at the max of the condition of your outer.
Also, you only need the System.out.print() on the inner loop.
for (int j = 0; j < i; j++) {
for (int k = 0; k < i; k++) {
System.out.print("x");
}
// When you're done printing the "x"s for the row, start a new row.
System.out.print("\n");
}
You are using the same loop counter for both loops, i2. So, when your inner loop executes, you are increasing the value of i2 by 1. This continues until i2 gets to your designated stop point. Then the inner loop ends. It then returns to the outer loop, and the outer loop checks if i2 is past the stop point. Since you increased the value of i2 in the inner loop, it is already past the cutoff point, and the outer loop stops.
To fix this, use separate variables for each loop. See below. I use i for the outer loop, j for the inner loop, and number as the cutoff point.
public static void main(String[] args) throws Exception {
int number = 4;
for (int i = 0; i < number; i++) {
for (int j = 0; j < number; j++) {
System.out.print("X");
}
System.out.println();
}
}
System.out.println("Give me a number : ");
Scanner kb = new Scanner(System.in);
int size = kb.nextInt();
int height = size;
int width = size;
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
System.out.print("X");
}
System.out.println();
}

Java exercise - display table with 2d array

I'm struggling to finish a java exercise, it involves using 2d arrays to dynamically create and display a table based on a command line parameter.
Example:
java table 5
+-+-+-+-+-+
|1|2|3|4|5|
+-+-+-+-+-+
|2|3|4|5|1|
+-+-+-+-+-+
|3|4|5|1|2|
+-+-+-+-+-+
|4|5|1|2|3|
+-+-+-+-+-+
|5|1|2|3|4|
+-+-+-+-+-+
What i have done so far:
public static void main(String[] args) {
int num = Integer.parseInt(args[0]);
String[][] table = new String[num*2+1][num];
int[] numbers = new int[num];
int temp = 0;
for(int i=0; i<numbers.length; i++)
numbers[i] = i+1;
// wrong
for(int i=0; i<table.length; i++){
for(int j=0; j<num;j++){
if(i%2!=0){
temp=numbers[0];
for(int k=1; k<numbers.length; k++){
numbers[k-1]=numbers[k];
}
numbers[numbers.length-1]=temp;
for(int l=0; l<numbers.length; l++){
table[i][j] = "|"+numbers[l];
}
}
else
table[i][j] = "+-";
}
}
for(int i=0; i<table.length; i++){
for(int j=0; j<num; j++)
System.out.print(table[i][j]);
if(i%2==0)
System.out.print("+");
else
System.out.print("|");
System.out.println();}
}
This doesn't work, since it prints 1|2|3|4 in every row, which isn't what I need. I found the issue, and it's because the first for loop changes the array order more times than needed and basically it returns as it was at the beginning.
I know that probably there's a way to achieve this by writing more code, but I always tend to nest as much as possible to "optimize" the code while I write it, so that's why I tried solving this exercise by using less variables and loops as possible.
You are too complex. Hard to find your error. Straight code follows:
public static void main(String[] args) {
//int num = Integer.parseInt(args[0]);
int num = 5; // for test
// creating 2d array
int[][] figures = new int[num][num];
// filling the array
for(int row=0; row<figures.length; ++row) {
for(int col=0; col<figures[row].length; ++col) {
figures[row][col] = (row + col) % num + 1;
}
}
// printing the array
for(int row=0; row<figures.length; ++row) {
// printing border
for(int col=0; col<figures[row].length; ++col) {
System.out.print("+-");
}
System.out.println("+");
// printing data row
System.out.print("|");
for(int col=0; col<figures[row].length; ++col) {
System.out.print(figures[row][col]);
System.out.print("|");
}
System.out.println();
}
// printing final border
for(int col=0; col<figures[0].length; ++col) {
System.out.print("+-");
}
System.out.println("+");
}
public static void main(String args[]){
int dimension = Integer.valueOf(args[0]);
int[][] twoDimArray = new int[dimension][dimension];
for(int i=0;i<dimension;i++){
for(int j=0;j<dimension;j++){
System.out.print("|"+((i+1)%(dimension+1)));
} //end of j loop
} //end of i loop
} //end of main
The above is only the logic for printing the numbers in the specified sequence.
The other design pattern ( +-+ ) thing i guess u can manage.
the following codes will initialize a 2d int array for the data (1-5 in your example). and print the table. note that the table structure was not save in a String 2d-array. just print the table out. see comments in line.
public static void main(String[] args){
final int num = 5; //hardcoded 5, just for testing.
final int[][] data = new int[num][num];
for (int r = 0; r < data.length; r++) {
for (int c = 0; c < data[r].length; c++) {
final int t = r + c + 1;
data[r][c] = t <= num ? t : t - num;
}
}
// now we have all int data in data 2D-array
// here is the +-+- line
final StringBuilder sb = new StringBuilder("+");
for (int i = 0; i < data.length; i++)
sb.append("-+");
// now print the table
for (int r = 0; r < data.length; r++) {
System.out.println(sb.toString());
for (int c = 0; c < data.length; c++)
System.out.print("|" + data[r][c]);
System.out.println("|");
}
System.out.println(sb.toString());
}
output:
if you give num=9 as argument. the codes above will print:
+-+-+-+-+-+-+-+-+-+
|1|2|3|4|5|6|7|8|9|
+-+-+-+-+-+-+-+-+-+
|2|3|4|5|6|7|8|9|1|
+-+-+-+-+-+-+-+-+-+
|3|4|5|6|7|8|9|1|2|
+-+-+-+-+-+-+-+-+-+
|4|5|6|7|8|9|1|2|3|
+-+-+-+-+-+-+-+-+-+
|5|6|7|8|9|1|2|3|4|
+-+-+-+-+-+-+-+-+-+
|6|7|8|9|1|2|3|4|5|
+-+-+-+-+-+-+-+-+-+
|7|8|9|1|2|3|4|5|6|
+-+-+-+-+-+-+-+-+-+
|8|9|1|2|3|4|5|6|7|
+-+-+-+-+-+-+-+-+-+
|9|1|2|3|4|5|6|7|8|
+-+-+-+-+-+-+-+-+-+
you have make it more complicated try this Simple code :
enter code here
public static void main(String[] args)
{
int n = 5 ;
for(int i = 1 ; i <= n ;i++)
{
for(int l = 0 ; l < n;l++)
System.out.print("+-");
System.out.print("\n|");
for(int j = i ; j <=n;j++ )
{
System.out.print(j+"|");
}
for(int k = 1 ; i >= 2 && k <=i-1;k++)
{
System.out.print(k+"|");
}
System.out.println();
}
}

Categories

Resources