nested while-loop that doesn't match the condition - java

I am trying to make a program that print the following numbers :
1 1
1 2
1 3
1 4
2 1
2 2
2 3
2 4
The code is
public class JavaApplication8 {
public static void main(String[] args) {
int i = 1;
int j = 1;
while (i <= 2 && j <= 4) {
while (i <= 2 && j <= 4) {
System.out.printf("%d%d\n", i, j);
j++;
}
j = j - 4;
i++;
System.out.printf("%d%d\n", i, j);
j++;
}
}
}
The program prints this
1 1
1 2
1 3
1 4
2 1
2 2
2 3
2 4
3 1
I don't know why this is happening behind the condition inside while says that it i must be smaller or equal 2

It's outputting that final 3 1 because your final println statement (indicated below) is unconditional. So after incrementing i to 3, you still run that statement. The while condition only takes effect afterward, which is why it then stops after printing that.
public class JavaApplication8 {
public static void main(String[] args) {
int i = 1;
int j = 1;
while (i <= 2 && j <= 4) {
while (i <= 2 && j <= 4) {
System.out.printf("%d%d\n", i, j);
j++;
}
j = j - 4;
i++;
System.out.printf("%d%d\n", i, j); // <=== This one
j++;
}
}
}
That whole thing can be dramatically simpler, though:
public class JavaApplication8 {
public static void main(String[] args) {
for (int i = 1; i <= 2; ++i) {
for (int j = 1; j <= 4; ++j) {
System.out.printf("%d%d\n", i, j);
}
}
}
}
Live Example

Related

half pyramid inverted with even number

half the pyramid is inverted with an even number, and each line omits the starting and ending numbers, so that the output expectation are as shown below.
Expected output
2 4 6 8 10
4 6 8
6
but I have tried my code below with the results that do not match my expectations.
My code
public static void main(String[] args) {
int rows = 5;
for (int i = rows; i >=1 ; i--) {
for (int j = 1; j <=2*i ; j++) {
if (j % 2 == 0){
System.out.print(j + " ");
}
}
System.out.println();
}
}
My output
2 4 6 8 10
2 4 6 8
2 4 6
2 4
2
Question:
how to solve the problem is?
You need to change the starting value of j as well and limit how often your first loop runs depending on rows:
int rows = 5;
for (int i = rows; i >= rows / 2; i--) {
for (int j = 2 + 2 * (rows - i); j <= 2 * i; j += 2) {
System.out.print(j + " ");
}
System.out.println();
}
Currently, you are starting the inner loop as int j = 1. Instead of a fixed start, it should be variable.
Replace
int j = 1;
with
int j = 2 * (rows - i + 1) - 1;
The starting condition of j should depend on i, also you can remove the if using j += 2 as increment statement
int rows = 5;
for (int i = rows; i >= 1; i--) {
for (int j = 2 * (rows - i + 1); j <= 2 * i; j += 2) {
System.out.print(j + " ");
}
System.out.println();
}
'rows' is a bad name. Can you see why?
here's the code:
public static void main(String[] args) {
int columns = 5;
for (int currentColumn = 0; currentColumn < columns ; currentColumn++) {
for (int j = currentColumn; j < columns-currentColumn ; j++) {
System.out.print((2*j+2) + " ");
}
System.out.println();
}
}
First, try to understand the pattern. For each iteration, the number of elements in a column is decreasing by 2. So consider the below code
public static void main(String[] args) {
int input = 5, multiplier = 2;
for(int numberOfRows = input; numberOfRows >= 1; numberOfRows -= 2) {
for(int columns = 1; columns <= numberOfRows; columns += 1) {
System.out.print(columns * multiplier + "\t");
}
System.out.println();
}
}

How do i put the other java number triangle side by side

So i was trying this code i found on the internet that let me make number triangles, the codes are like so
public class StarsAndDraws {
public static void main(String[] args) {
for (int i = 0; i <= 4; i++) {
for (int j = 4; j >= 1; j--){
if (j > i){
System.out.print(" ");
} else {
System.out.print(i - j + 1);
}
}
System.out.println();
}
}
}
the output looks like this
1
1 2
1 2 3
1 2 3 4
but this is the output im looking for
1
1 2
1 1 2 3
1 2 1 2 3 4
i have no idea how, help and explanation is appreciated because id like to do this to other kinds of stuff aswell
To print first 1/ 1 2, it is needed to define another loop for that one too.
class Main {
public static void main(String[] args) {
for (int i = 1; i <= 4; i++) {
if (i < 3) {
System.out.print(" ".repeat(9));
} else {
System.out.print(" ".repeat((4 - i) * 2));
for (int j = 1; j <= i - 2; j ++) {
System.out.print(j);
System.out.print(" ");
}
System.out.print(" ".repeat(6));
}
System.out.print(" ".repeat(2 * (4 - i)));
for (int j = 1; j <= i; j ++) {
System.out.print(j);
System.out.print(" ");
}
System.out.println();
}
}
}

Java increment declaration in for loop

public class F2E12 {
public static final int DIM = 5;
public static void main(String[] args) {
printMatrix(DIM);
}
public static void printMatrix(int n) {
int i = 0;
int j = 0;
for(;i<=n;i++) {
for(;j<=n;j++) {
System.out.print(j + " ");
}
System.out.print("\n");
}
}
}
I want to print a matrix which increments the first number of each row by one.
The above code should produce:
0 1 2 3 4 5
1 0 1 2 3 4
2 1 0 1 2 3
3 2 1 0 3 4
4 3 2 1 0 1
5 4 3 2 1 0
Instead it prints. "0 1 2 3 4 5"
public static void printMatrix(int n) {
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= n; j++) {
System.out.print(Math.abs(j - i) + " ");
}
System.out.print("\n");
}
}
Your current code doesn't work because j hits n on the first iteration of i. You could move j into the loop like
// int j = 0;
for (; i <= n; i++) {
int j = 0;
for (; j <= n; j++) {
to fix that.

Display a box of increasing number with order

CODE
int rows=3, columns=3, i, j;
for(i = 1; i <= rows; i++)
{
for(j = 1; j <= columns; j++)
{
if(i == 1 || i == rows || j == 1 || j == columns)
{
System.out.print(count);
count++;
}
else
{
System.out.print(" ");
}
}
System.out.print("\n");
}
The following piece of code outputs the following:
OUTPUT
123
4 5
678
What I'm trying to achieve is the following:
123
8 4
765
Basically creating a board game which has to start from one position and end at the same position completing a full circle., in this case a square.
Any Ideas ??
After some experiments, this could work:
public static void printBox(int rows, int columns) {
int sumOfColumns = 2 * columns + rows - 1;
int sumOfRow = 2 * columns + 2 * rows - 2;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= columns; j++) {
if (i == 1) {
System.out.printf(String.format("%3d", j));
} else if (j == 1) {
System.out.printf(String.format("%3d", sumOfRow - (i + j - 1)));
} else if (j == columns) {
System.out.printf(String.format("%3d", i + j - 1));
} else if (i == rows) {
System.out.printf(String.format("%3d", sumOfColumns - j));
} else {
System.out.print(" ");
}
}
System.out.print("\n");
}
System.out.print("\n");
}
Test case:
public static void main(String[] args) {
printBox(3, 3);
printBox(4, 4);
printBox(3, 4);
}
Result:
1 2 3
8 4
7 6 5
1 2 3 4
12 5
11 6
10 9 8 7
1 2 3 4
10 5
9 8 7 6
Consider creating a 2 dimensional array:
gameBoard[3][3];
then populate that board with the desired values. After the gameboard is complete, you can write another function to print the board.

Empty diamond shape with numbers

So I have been asked this question and I could only solve the top part of the code, I am stuck on the bottom part.
Write a Java program called EmptyDiamond.java that contains a method that takes an integer n and prints a empty rhombus on 2n − 1 lines as shown below. Sample output where n = 3:
1
2 2
3 3
2 2
1
Here's my code so far:
public static void shape(int n) {
//TOP PART
for (int i = 1; i <= (n - 1); i++) {
System.out.print(" ");
}
System.out.println(1);
for (int i = 2; i <= n; i++) {
for (int j = 1; j <= (n - i); j++) {
System.out.print(" ");
}
System.out.print(i);
for (int j = 1; j <= 2 * i - n + 1; j++) {
System.out.print(" ");
}
System.out.println(i);
}
//BOTTOM PART (The messed up part)
for (int i = n + 1; i <= 2 * n - 2; i++) {
for (int j = 1; j <= n - i; j++) {
System.out.print(" ");
}
System.out.print(i);
for (int j = 1; j <= n; j++) {
System.out.print(" ");
}
System.out.print(i);
}
for (int i = 1; i <= (n - 1); i++) {
System.out.print(" ");
}
System.out.println(1);
}
public static void main(String[] args) {
shape(4);
}
Maybe a little bit late, but because the bottom part of your message is just the first part mirrored you can use a Stack to print the message in reverse order:
public static void main(String[] args) {
int maxNumber = 3;
Stack<String> message = new Stack<>();
// upper part
for (int row = 0; row < maxNumber; row++) {
int prefix = maxNumber - (row + 1);
int spaces = row >= 2 ? row * 2 - 1 : row;
String line = getLine(row, prefix, spaces);
System.out.println(line);
if (row != maxNumber - 1)
message.add(line);
}
// bottom part
while (!message.isEmpty())
System.out.println(message.pop());
}
public static String getLine(int row, int prefix, int spaces) {
StringBuilder line = new StringBuilder("_".repeat(prefix));
line.append(row + 1);
if (row != 0) {
line.append("_".repeat(spaces));
line.append(row + 1);
}
return line.toString();
}
Output:
__1
_2_2
3___3
_2_2
__1
You can of course use any method you want to fill the stack (i.e. to generate the upper part of your message) like with the method this question suggessted. This upper part I describe contains the first line (inclusive) up to the middle line (exclusive).
Here is the program for printing empty diamond:
int n = 3; //change the value of n to increase the size of diamond
int upperCount = 1;
for (int i = n; i >= 1; i--) {
for (int j = i; j >= 1; j--) {
System.out.print(" ");
}
System.out.print(upperCount);
for (int j = 0; j <= upperCount - 2; j++) {
System.out.print(" ");
}
for (int j = 0; j <= upperCount - 2; j++) {
System.out.print(" ");
}
if (upperCount != 1) {
System.out.print(upperCount);
}
upperCount++;
System.out.print("\n");
}
int lowerCount = n - 1;
for (int i = 1; i <= n - 1; i++) {
for (int j = 0; j <= i; j++) {
System.out.print(" ");
}
System.out.print(lowerCount);
for (int j = 0; j <= lowerCount - 2; j++) {
System.out.print(" ");
}
for (int j = 0; j <= lowerCount - 2; j++) {
System.out.print(" ");
}
if (lowerCount != 1) {
System.out.print(lowerCount);
}
lowerCount--;
System.out.print("\n");
}
Do following changes in the Bottom Part of your code:
int lowerCount = n - 1;
for (int i = n - 1; i >= 2; i--) {
for (int j = 1; j <= (n - i); j++) {
System.out.print(" ");
}
System.out.print(i);
for (int j = 1; j <= lowerCount; j++) {
System.out.print(" ");
}
System.out.print(i);
lowerCount -= 2;
}
You can print an empty diamond shape with numbers using two nested for loops over rows and columns from -n to n. The diamond shape is obtained when iAbs + jAbs == n:
int n = 2;
for (int i = -n; i <= n; i++) {
// absolute value of 'i'
int iAbs = Math.abs(i);
for (int j = -n; j <= n; j++) {
// absolute value of 'j'
int jAbs = Math.abs(j);
// empty diamond shape
System.out.print(iAbs + jAbs == n ? jAbs + 1 : " ");
if (j < n) {
System.out.print(" ");
} else {
System.out.println();
}
}
}
Output:
1
2 2
3 3
2 2
1
You can separately define width and height:
int m = 4;
int n = 2;
int max = Math.max(m, n);
for (int i = -m; i <= m; i++) {
// absolute value of 'i'
int iAbs = Math.abs(i);
for (int j = -n; j <= n; j++) {
// absolute value of 'j'
int jAbs = Math.abs(j);
// empty diamond shape
System.out.print(iAbs + jAbs == max ? jAbs + 1 : " ");
if (j < n) {
System.out.print(" ");
} else {
System.out.println();
}
}
}
Output:
1
2 2
3 3
3 3
2 2
1
See also:
• Filling a 2d array with numbers in a rhombus form
• How to print a diamond of random numbers?
java-11
Using String#repeat introduced as part of Java-11, you can do it using a single loop.
public class Main {
public static void main(String[] args) {
int n = 3;
for (int i = 1 - n; i < n; i++) {
int x = Math.abs(i);
System.out.println(" ".repeat(x) + (n - x)
+ " ".repeat(Math.abs((n - x) * 2 - 3))
+ ((i == 1 - n || i == n - 1) ? "" : (n - x)));
}
}
}
Output:
1
2 2
3 3
2 2
1
You can print a variant of the diamond simply by increasing the amount of space by one character:
public class Main {
public static void main(String[] args) {
int n = 3;
for (int i = 1 - n; i < n; i++) {
int x = Math.abs(i);
System.out.println(" ".repeat(x) + (n - x)
+ " ".repeat(Math.abs((n - x) * 2 - 3))
+ ((i == 1 - n || i == n - 1) ? "" : (n - x)));
}
}
}
Output:
1
2 2
3 3
2 2
1
Alternative solution:
public static void main(String[] args) {
int n = 7;
for (int i = -n; i <= n; i++) {
for (int j = -n; j <= n; j++) {
// edge of the diamond
int edge = Math.abs(i) + Math.abs(j);
// diamond shape with numbers
if (edge == n) System.out.print(n - Math.abs(i) + 1);
// beyond the edge && in chessboard order || vertical borders
else if (edge > n && (i + j) % 2 != 0 || Math.abs(j) == n)
System.out.print("*");
// empty part
else System.out.print(" ");
}
System.out.println();
}
}
Output:
** * * 1 * * **
* * * 2 2 * * *
** * 3 3 * **
* * 4 4 * *
** 5 5 **
* 6 6 *
*7 7*
8 8
*7 7*
* 6 6 *
** 5 5 **
* * 4 4 * *
** * 3 3 * **
* * * 2 2 * * *
** * * 1 * * **
See also: How to print a given diamond pattern in Java?
Solution: Java program called EmptyDiamond.java that contains a method that takes an integer n and prints a empty rhombus on 2n − 1 lines.
public class EmptyDiamond {
public static void main(String[] args) {
shape(3); // Change n to increase size of diamond
}
public static void shape(int n) {
int max = 2 * n - 1; // length of the diamond - top to bottom
int loop = 0; // with of each loop. initialized with 0
for (int i = 1; i <= max; i++) {
int val = 0;
if (i <= n) {
loop = n + i - 1;// e.g. when i = 2 and n = 3 loop 4 times
val = i; // value to be printed in each loop ascending
} else {
loop = n + (max - i); //e.g. when i = 4 and n = 3 loop 4 times
val = max - i + 1; // value to be printed in each loop descending
}
for (int j = 1; j <= loop; j++) {
// (value end of loop)
// || (value in the beginning when i <= n)
// || (value in the beginning when i > n)
if (j == loop
|| j == (n - i + 1)
|| j == (n - val + 1)) {
System.out.print(val); // Print values
} else {
System.out.print(" "); // Print space
}
}
System.out.println(); // Print next line
}
}
}
Output when n = 3:
1
2 2
3 3
2 2
1
Stream-only function:
public static void printEmptyDiamond(int n) {
IntStream.range(1, 2*n)
.map(i-> i > n ? 2*n-i : i)
.mapToObj(i -> " ".repeat(n-i) + i + (i>1 ? " ".repeat(2*(i-1)-1)+i : ""))
.forEach(System.out::println);
}
Example output (printEmptyDiamond(7)):
1
2 2
3 3
4 4
5 5
6 6
7 7
6 6
5 5
4 4
3 3
2 2
1
With explainations:
public static void printEmptyDiamond(int n) {
IntStream.range(1, 2*n)
.map(i-> i > n? 2*n-i : i) // numbers from 1 to n ascending, then descending to 1 again
.mapToObj(i -> " ".repeat(n-i) // leading spaces
+ i // leading number
+ (i>1 ? // only when number is > 1
" ".repeat(2*(i-1)-1) // middle spaces
+ i // trailing number
: ""))
.forEach (System.out::println);
}
I did it for fun, here's the code :
import java.util.Scanner;
public class Diamond {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int num = read.nextInt();
read.nextLine();
//TOP
for(int i = 1;i<=num;i++) {
//LEFT
for(int k = i; k<num;k++) {
if ( k % 2 == 0 ) {
System.out.print(" ");
}
else {
System.out.print(" ");
}
}
if(i>1) {
for(int j =1;j<=i;j++) {
if (j==1 || j== i) {
for(int u=0;u<j;u++) {
System.out.print(" ");
}
System.out.print(i);
}
else {
System.out.print(" ");
}
}
System.out.println("");
}
else {
System.out.println(" "+i);
}
}
//BOTTOM
for(int i = num-1;i>0;i--) {
for(int k = i; k<num;k++) {
if ( k % 2 == 0 ) {
System.out.print(" ");
}
else {
System.out.print(" ");
}
}
if(i>1) {
for(int j =1;j<=i;j++) {
if (j==1 || j== i) {
for(int u=0;u<j;u++) {
System.out.print(" ");
}
System.out.print(i);
}
else {
System.out.print(" ");
}
}
System.out.println("");
}
else {
System.out.println(" "+i);
}
}
}
}
And the output :
7
1
2 2
3 3
4 4
5 5
6 6
7 7
6 6
5 5
4 4
3 3
2 2
1
Having seen the other answers, there's a whole load of loops I could've skipped. Just decided to wing it at the end and do it as quick as possible.

Categories

Resources