Using nested FOR loop for printing square by numbers - java

I'm trying to print square by using nested for loop. It is needed square to look like sequence numbers. Actually I didn't receive square. Please see attached file to understand my goal- red border.
public class Day22022014 {
public static void main(String[] args){
Scanner in=new Scanner(System.in);
int n=in.nextInt();
for(int row=1; row<=n; row++){
System.out.printf("%d %n", row);
for(int col=row; col<2*n; col++){
System.out.printf("%d ", col);
}
}}}

You have a few errors there. The first printf is incorrectly outputting a number, you only need to make a new line, all numbers should be outputted inside the inner for.
Secondly, the condition col < 2 * n is wrong, you only want to go up to row + n - 1.
I suggest you go through this and try to understand, how do the indices row and col change in each iteration.
for(int row = 1; row <= n; row++){
for(int col = row; col <= (row + n - 1); col++){
System.out.printf("%d ", col);
}
System.out.println();
}

Related

How to dynamically format Strings in Java

The following program prints the multiplication table 9xN which N is given by the user. My cells are fixed to be aligned only when the product is 2 numbers long.
What can I do so the cells will be aligned with any size of numbers?
public static void main(String[] args) {
//Reading the number n.
System.out.print("Give a number: ");
int n = StdIn.readInt();
//Validating the number.
while(n<1) {
System.out.println("Please give a number greater or equal to 1");
n = StdIn.readInt();
}
/*---------------------------------
*
*Lines 27-36 -> Creating the first
*line and the first line's design.
*
----------------------------------*/
for (int i = 1; i <= n; i++) {
System.out.printf(" %-4d", i);
}
System.out.println();
System.out.print(" +");
for (int i = 1; i <= n; i++) {
System.out.print("-------+");
}
System.out.println();
/*----------------------------------
*
*Lines 45-58 -> Printing the product
*of the numbers and the design of
*the table.
*
----------------------------------*/
for (int i = 1; i <=9 ; i++) {
System.out.print(i + " | ");
for (int j = 1; j <= n; j++) {
int a = (i * j);
String b = " | ";
System.out.printf("%2d %s", a, b);
}
System.out.println();
System.out.print(" +");
for (int k = 1; k <= n; k++) {
System.out.print("-------+");
}
System.out.println();
}
}
}
What can I do so the cells will be aligned with any size of numbers?
Not Aligned Cells
Aligned Cells
Thanks in advance.
To expand #Thomas Weller's comment a little, you need to separate the table cell value calculation loop from the table printing loop because you need to know the maximum number of digits in any cell before you start printing out the table so the 2 in %2d can be that max value instead.
EDIT: You will also need to know that max value in order to create the correct cell width instead of hard coding "-------+"

2D Array Display

This question relates to my 2D array display, which currently looks something like this.
A B C D
1: 0 0 0 0
2: 0 0 0 0
3: 0 0 0 0
I am trying to get location (0,0) to change to the number 1 as this will be the start of my count.
However it won't change and remains as a zero, here is my code.
int[][] chessBoard = new int[3][4];
int rowhead = 1;
TextIO.put(" ");
for (int col = 0; col < chessBoard[0].length; col++)
TextIO.putf("%4s",((char) ('A' + col)));
TextIO.putln();
for (int [] row:chessBoard){
TextIO.put(rowhead++ + ":");
for (int griddisplay:row)
TextIO.putf("%4d", griddisplay);
TextIO.putln();
chessBoard [0][0] = 1;
Now this keeps my coordinates (o, o) displaying a zero, however if I change this
chessBoard [0][0] = 1;
to this
chessBoard [1][0] = 1;
Then the grid does change accordingly to
A B C D
1: 0 0 0 0
2: 1 0 0 0
3: 0 0 0 0
Where am I going wrong?
Your code works fine, I just added a few methods and altered output
public class Chessboard
{
public static void main(String[] args)
{
int[][] chessBoard = new int[3][4];
print(chessBoard);
chessBoard [0][0] = 1;
print(chessBoard);
chessBoard [1][0] = 1;
print(chessBoard);
clear(chessBoard);
print(chessBoard);
}
public static void print(int[][] chessBoard)
{
int rowhead = 1;
System.out.print("\n ");
for (int col = 0; col < chessBoard[0].length; col++)
System.out.printf("%4s",((char) ('A' + col)));
System.out.println();
for (int[] row : chessBoard)
{
System.out.print(rowhead++ + ":");
for (int griddisplay : row)
System.out.printf("%4d", griddisplay);
System.out.println();
}
System.out.println();
}
public static void clear(int[][] chessBoard)
{
for (int row = 0; row < chessBoard.length; row++)
for(int col = 0; col < chessBoard[row].length; col++)
chessBoard[row][col] = 0;
}
}
Move your chessBoard [0][0] = 1; right below the TextIO.put(rowhead++ + ":");:
int[][] chessBoard = new int[3][4];
int rowhead = 1;
TextIO.put(" ");
for (int col = 0; col < chessBoard[0].length; col++)
TextIO.putf("%4s",((char) ('A' + col)));
TextIO.putln();
for (int [] row:chessBoard) {
TextIO.put(rowhead++ + ":");
chessBoard[2][3] = 1;
for (int griddisplay : row){
TextIO.putf("%4d", griddisplay);
}
TextIO.putln();
}
and it will work propertly =).
You appear to have some formatting issues but from the gist of it:
You are constructing your chess board as an array [3][4] and by the looks of it that is 3 'rows' and 4 'columns' so your first index is your row number and second is column number.
You loop through the first 'row' to get the length (4) so are outputting 4 columns - correctly I am assuming.
You then move to printing the chessboard (though I don't see the matching curly brace }). First you loop across rows and then across columns.
For example:
for (int [] row:chessBoard) {
TextIO.put(rowhead++ + ":");
for (int griddisplay:row)
TextIO.putf("%4d", griddisplay);
TextIO.putln();
chessBoard [0][0] = 1;
}
If this is your code, the first loop starts processing the first row. It loops through the columns for the first row, THEN sets [0][0] to be 1... but you've already printed that so it won't be shown. If you replace it with [1][0], it actually sets that BEFORE printing the second row so correctly shows the value.
As a final tip, the curly braces specify the scope of the for loop. If you omit the braces, the loop only runs the statement immediately after it. A habit a lot of programmers get in to is to always explicitly use braces to avoid easy mistakes.

How to reverse a loop

So basically my assignment was to print a list of stars.
public class Practice_6_2
{
public static void main (String[] args)
{
final int MAX_ROWS = 10;
for (int row = 1; row <= MAX_ROWS; row++)
{
for (int star = 1; star <= row; star++)
System.out.print ("*");
System.out.println();
}
}
}
But when it prints, it is actually the opposite. How would I fix this?
Edit:
When I run the program, it will print one star on the first line, two stars on the second, and so forth until it reaches the tenth line. I need it to print ten stars on the first line, nine on the second, and so forth. Kind of reversing it.
You could reverse the direction you iterate on row. Change
for (int row = 1; row <= MAX_ROWS; row++)
to something like
for (int row = MAX_ROWS; row >= 1; row--)
to start at MAX_ROWS and descend to 1.

Java pyramid of numbers - version 2

I'm reading a book and before I go to next chapter, I want to solve every exercise from current one. I have a problem with creating this output (the number of rows must be between 11 and 20)
I almost have it, even when I think my code is pretty bad and I could get it in less lines.
public class piramide {
public static void main(String args[]){
int max, n;
max = 20;
n=1;
for (int min=11; min<=max; min++){
if (n>9) n-=10;
int x=n-1;
int x2=n-1;
int b=min-1;
for (int j=1; j<min; j++){
while (b<max-1) {
System.out.print(" ");
b++;
}
System.out.print(x);
x--;
if (x<0) x=9;
}
System.out.print("A"+n+"A");
for (int j=1; j<min; j++){
System.out.print(x2);
x2--;
if (x2<0) x2=9;
}
System.out.println();
n+=2;
}
}
}
This is my current code and this is the output:
0987654321A1A0987654321
21098765432A3A21098765432
432109876543A5A432109876543
6543210987654A7A6543210987654
87654321098765A9A87654321098765
098765432109876A1A098765432109876
2109876543210987A3A2109876543210987
43210987654321098A5A43210987654321098
654321098765432109A7A654321098765432109
8765432109876543210A9A8765432109876543210
The problem I'm having is that the left part of the pyramid should be reversed. For example in the first row it should start at 0 (from the A1A) and finish in 1 but it starts in 1 and finish in 0, any idea how can I turn it to the other side?
Thanks to all of you who helped me ^^.
Oh, and the caps A are just so I could find the number easier in the output.
Have you worked the problem out?
The code will be much easier to understand with a couple changes...
max, min, and especially the single letter variables like n should have names that help describe what they are. This may also help you think about the problem when you don't have to keep in mind what all those random letters mean.
n I will rename to rowIndex
max I will rename to totalRows
min I will rename to columnIndex
Starting with that we have
public static void main(String args[])
{
int totalRows = 20;
int rowIndex = 1;
int columnIndex = 1;
//we look ready to start at row 1, column 1!
}
Now, this section of your code:
for (int min=11; min<=max; min++){
if (n>9) n-=10;
int x=n-1;
int x2=n-1;
int b=min-1;
for (int j=1; j<min; j++){
while (b<max-1) {
System.out.print(" ");
b++;
}
You are setting min, or, the columnIndex, to start at 11, because that is the "middle" of the pyramid. Then you print out spaces to catch up to the columnIndex.
x = rowIndex - 1;
x2 = rowIndex - 1;
b = columnIndex - 1;
j and b are now like a second and third column index, which is catching up to the actual columnIndex
Look at this example of how your for loop works:
for (int j=1; j <min; j++) { // j = 1;
while (b<max-1) { // 10 < 19
System.out.print(" "); // print space
b++; // b = 11
// 11 < 19
// print space
// b = ...(*skip to the end*) 19
// j = 2
// b is still 19, doesn't print anything
// j = 3, etc.
}
System.out.print(x);
x--;
if (x<0) x=9;
}
In other words, j and b are unnecessary because we already have a columnIndex we can use. Let's do some more renaming of variables.
x I will rename to printValue
x2 will be unnecessary, we only need one printValue, However, I will be adding a totalColumns to the beginning of our main method.
So now our finished code will look like:
public static void main(String args[])
{
int totalRows = 20;
int totalColumns = (totalRows * 2) - 1; //added totalColumns, notice the number of columns increases by two with each row and we start with 1 column.
int rowIndex = 0;//easier for looping to start with zero
int columnIndex = 0;
int printValue = 0;
while (rowIndex < totalRows) // we will want to spin through every row
{
//notice there is no limit to the length of a variable name!
int numberOfValuesInRow = (rowIndex*2) + 1;
int numberOfSpacesToOffsetOnEachSide = (totalColumns - numberOfValuesInRow) / 2;
//Print Spaces before the numbers in this row
for (int i = 0; i < numberOfSpacesToOffsetOnEachSide; i++) //i is commonly used to stand for index in a single for loop
{
System.out.print(" ");
columnIndex++; //keep track of columnIndex so we know when we are at the middle of the columns
}
//Print numbers in this row
for (int i = 0; i < numberOfValuesInRow; i++)
{
if (columnIndex < (totalColumns/2) + 1) { //depending on columnIndex position, increase or decrease printValue
printValue++;
} else {
printValue--;
}
System.out.print(printValue%10); //Print printValue, the % will return the remainder of (printValue/10)
columnIndex++;
}
System.out.println(); //start next line
columnIndex = 0; //reset columnIndex for the next row
rowIndex++;
}
}

Printing Custom 2d Array as a Matrix

Given my current code, how could I output it in matrix format? My current output method simply lists the arrays in a straight line. However I need to stack them in their corresponding input parameters so a 3x3 input produces a 3x3 output. Thank you!
import java.util.Scanner;
for(int row = 0; row < rows; row++){
for( int column = 0; column < columns; column++){
System.out.print(array2d[row][column] + " ");
}
System.out.println();
}
This will print out a line of one row and then move onto the next row and print out its contents, etc... Tested with the code that you provided and works.
EDIT - Added the code for the way you wanted it:
public static void main(String[] args) {
Scanner scan =new Scanner(System.in); //creates scanner object
System.out.println("How many rows to fill?"); //prompts user how many numbers they want to store in array
int rows = scan.nextInt(); //takes input for response
System.out.println("How many columns to fill?");
int columns = scan.nextInt();
int[][] array2d=new int[rows][columns]; //array for the elements
for(int row=0;row<rows;row++)
for (int column=0; column < columns; column++)
{
System.out.println("Enter Element #" + row + column + ": "); //Stops at each element for next input
array2d[row][column]=scan.nextInt(); //Takes in current input
}
System.out.println(Arrays.deepToString(array2d));
String[][] split = new String[1][rows];
split[0] = (Arrays.deepToString(array2d)).split(Pattern.quote("], [")); //split at the comma
for(int row = 0; row < rows; row++){
System.out.println(split[0][row]);
}
scan.close();
}
for (int i =0; i < rows; i++) {
for (int j = 0; j < columns ; j++) {
System.out.print(" " + array2d[i][j]);
}
System.out.println("");
}

Categories