Java printing patterns using for loops - java

I need to get the following pattern
have developed following code.
public static void main(String[] args) {
int number = 9;
for(int i=0;i<9;i++){
for(int j=0;j<18;j++){
if(number==6)
continue;
System.out.print(number);
}
if(number != 6)
System.out.println();
number--;
}
}
But I cant think about the logic to get the curved part of the pattern. Can Anyone give an opinion?

if (j < number || j >= 18 - number)
System.out.print(number);
else
System.out.print(" ");

You could try this:
public class CurveOutput {
public static void main(String args[]) {
int startNumber = 9;
for (int currentNum = startNumber; currentNum >= 0; currentNum--) {
StringBuilder line = new StringBuilder();
for (int i = 0; i < currentNum; i++) {
line.append(currentNum);
}
for (int i = 0; i < startNumber - currentNum; i++) {
line.append(" ");
}
System.out.println(line.toString() + line.reverse().toString());
}
}
}
this snippet produce:
999999999999999999
88888888 88888888
7777777 7777777
666666 666666
55555 55555
4444 4444
333 333
22 22
1 1

From my perspective it is really about programming on a correct level of abstraction.
The requirement is not to put as many spaces in the start or at the end, but rather to align the numbers to left or right. If there would be such functionality, it would be better and most likely more readable. And there is such:
public static void main(String args[]) {
int startNumber = 9;
for (int i = startNumber; i > 0; i--) {
String numberToPrint = Strings.repeat("" + i, i); // from Google Guava
String leftHalf = String.format("%-" + startNumber + "s", numberToPrint);
String rightHalf = String.format("%" + startNumber + "s", numberToPrint);
System.out.printf("%s%s%n", leftHalf, rightHalf);
}
}

Try this...
int num=9,save=9;
for(int i=1;i<10;i++)
{
for(int j=1;j<=18&&num!=6;j++)
{
int t=save-num;
if(((j<=(9-t)) || (j>(9+t))))
System.out.print(num);
else
System.out.print(" ");
}
num=num-1;
System.out.println("\n");
}

package q17;
public class Q17 {
public static void main(String[] args) {
int x = 9, y = 10;
for (int i = x; i >= 1; i--) {
if (i == 6) {
x--;
y++;
continue;
}
for (int j = 1; j <= 18; j++) {
if ((i != 9) && ((j >= x) && (j <= y))) {
System.out.print(" ");
} else {
System.out.print(i);
}
}
if (i != 9) {
x--;
y++;
}
System.out.println();
}
}
}

Related

Print pyramid of * in Java

I'm wondering if you could help me out. I'm trying to write a nested for loop in java that displays a number pyramid triangle that looks like
___________*#
__________*_*#
_________*___*#
________*_____*#
_______*_______*#
______*_________*#
_____*___________*#
____*_____________*#
___*_______________*#
__*_________________*#
_*___________________*#
***********************#
This is what I have so far:
class Triagle {
public static void printTriagle(int n) {
for (int i = 0; i < n; i++) {
for (int j = n - i; j > 1; j--) {
System.out.print(" ");
}
for (int j = 0; j <= i; j++) {
// printing stars
System.out.print("* ");
}
System.out.println();
}
}
public static void main(String[] args) {
printTriagle(12);//I want to set the triangle to be height of 12
}
}
My result is not equal to the expected output:
___________*#
__________*_*#
_________*_*_*#
________*_*_*_*#
_______*_*_*_*_*#
______*_*_*_*_*_*#
_____*_*_*_*_*_*_*#
____*_*_*_*_*_*_*_*#
___*_*_*_*_*_*_*_*_*#
__*_*_*_*_*_*_*_*_*_*#
_*_*_*_*_*_*_*_*_*_*_*#
*_*_*_*_*_*_*_*_*_*_*_*#
I have updated your code and added comments so that you can understand. Refer to the code below:
public static void printTriagle(int n) {
for (int i = 0; i < n; i++) {
for (int j = n - i; j > 1; j--) {
System.out.print("_");
}
String s = "_";
if (i + 1 >= n) // check if it is the last line
s = "*"; // change to print * instead of _
for (int j = 0; j <= i; j++) {
// printing stars
if (j == i)
System.out.print("*#"); // check if the last print of the line
else if (j == 0)
System.out.print("*" + s); // check if the first print of the line
else
System.out.print(s + s);
}
System.out.println();
}
}
Result:
___________*#
__________*_*#
_________*___*#
________*_____*#
_______*_______*#
______*_________*#
_____*___________*#
____*_____________*#
___*_______________*#
__*_________________*#
_*___________________*#
***********************#
Try this
public static void printTriagle(int n) {
for (int i = 0; i < n; i++) {
for (int j = n - i; j > 1; j--) {
System.out.print(" ");
}
for (int j = 0; j <= i; j++) {
// printing stars
if(i == (n-1)){
System.out.print("**");
}
else{
System.out.print((j == 0 || j == i) ? "* " : " ");
}
}
System.out.println();
}
}
Your issue is here:
for (int j=0; j<=i; j++){
// printing stars
System.out.print("* ");
}
Here, it prints a star for each number between 0 and i, but it only should print a star if it is exactly 0 or i.
Try something like this:
for (int j=0; j<=i; j++){
if ( i == n ) {
System.out.print("* ");
} else {
System.out.print(j == 0 || j == i ? "* " : " ");
}
}
EDIT: You may still have to adapt your code to get the bottom line printed correctly, in case that line has to be all stars
This is what you need to do:
public static void printTriagle(int n) {
for(int i = 0; i < n; i++) {
for(int j = 0; j < 2*n; j++) {
if(i == n-1) {
System.out.print((j != 2*n-1) ? "*" : "#");
}
else {
if(i+j == n-1) {
if(i == 0) {
System.out.print("*#");
break;
}
else {
System.out.print("*");
}
}
else if(j-i == n-1) {
System.out.print("*#"); break;
}
else {
System.out.print("_");
}
}
}
System.out.println();
}

(Java Number Pyramid) How do I get my numbers to have more spaces between them while lining up accurately when it is an integer is > 9?

I am having difficulty getting the desired output. I know there are problems that are similar to mine that is already posted, but I find it hard to relate my code to their solutions without a massive overhaul.
The solution for my class assignment:
Supposed to continue until every direction of pyramid equals 1
My second method "spaces" is redundant and I am not sure why. Any help would be appreciated.
Blockq
public static void main(String[] args) {
numPar();
spaces();
}
private static void spaces() {
int x = 0;
if(x > 0 && x < 10) {
System.out.print(" ");
} else if (x > 10 && x < 99) {
System.out.print(" ");
} else if (x > 99) {
System.out.print(" ");
}
}
private static void numPar() {
int spaces = 14;
for(int i = 0; i<= 7; i++) {
for(int u = 0; u<spaces; u++) {
System.out.print(" ");
}
spaces--;
spaces--;
for(int j = 0 ; j <i ; j++) {
System.out.print(""+ (int) Math.pow(2,j)+" ");
}
for(int k = i ; k >=0 ; k--) {
System.out.print(""+ (int) Math.pow(2,k)+" ");
}
System.out.println("");
}
}
}
I made every number take 3 places using String.format("%3s", (int) Math.pow(2, j)). You can make it dynamic by replacing the number 3 here with the length of the largest number you'll print. I also changed the number of spaces in your print statements. Here is the full code that prints an evenly spaced pyramid:-
public static void main(String[] args) {
numPar();
spaces();
}
private static void spaces() {
int x = 0;
if (x > 0 && x < 10) {
System.out.print(" ");
} else if (x > 10 && x < 99) {
System.out.print(" ");
} else if (x > 99) {
System.out.print(" ");
}
}
private static void numPar() {
int spaces = 14;
for (int i = 0; i <= 7; i++) {
for (int u = 0; u < spaces; u++) {
System.out.print(" ");
}
spaces--;
spaces--;
for (int j = 0; j < i; j++) {
System.out.print("" + String.format("%3s", (int) Math.pow(2, j)) + " ");
}
for (int k = i; k >= 0; k--) {
System.out.print("" + String.format("%3s", (int) Math.pow(2, k)) + " ");
}
System.out.println("");
}
}
String.format explanation:-
String.format("%3s", str) will print the string str, padding it with spaces, to make the total length 3 if it's less than 3. Note that you can write anything instead of 3 - I used 3 because your biggest number was of length 3.
So "A" will be printed as "_ _ A" (2 spaces), and "Ab" will be printed as "_ Ab" (1 space).
I just replaced str with your Math.pow(2, j).

How to get Number pattern in specific shape (java)?

I want to print number pattern like this..
but, I failed to get this triangle shape,and I am confused how to put spaces to get this shape -->
1
212
32123
4321234
Here's the code i tried so far
public class Ch {
public static void main(String[] args) {
int r =Integer.parseInt(args[0]);
for(int u=1;u<=r;u++)
{
for(int i=u;i>=1;i--)
{
System.out.print(i);
}
for(int i=2;i<=u;i++)
{
System.out.print(i);
}
System.out.println();
}
}
}
output of this code looks-like this
1
212
32123
4321234
Thanks
Just add one more step in you main loop before the other two:
for (int i = u; i < r; i++)
{
System.out.print(" ");
}
This will print spaces to make up for the "missing" numbers.
In regard to Mateusz' comment, look at this answer on how to pad your numbers with spaces to make them equally wide in case you go beyond 9:
static int padding;
public static void main(String[] args)
{
int r = Integer.parseInt(args[0]);
padding = Math.max(1, (int) Math.ceil(Math.log10(r)));
for (int u = 1; u <= r; u++)
{
for (int i = u; i < r; i++)
{
print(" ");
}
for (int i = u; i >= 1; i--)
{
print(i);
}
for (int i = 2; i <= u; i++)
{
print(i);
}
System.out.println();
}
}
private static void print(Object text)
{
System.out.print(String.format("%1$" + padding + "s", text));
}
using 2 for loops
package com.stackoverflow;
import java.util.Scanner;
public class Pyramid {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the pyramid limit value: ");
int limit = in.nextInt();
in.close();
for (int i = 0; i < limit; i++) {
for (int j = 0; j < limit + i; j++) {
if (j < limit -i-1)
System.out.print(" ");
else{
int temp = (limit-j > 0) ? limit-j : j-limit+2;
System.out.print(temp);
}
}
System.out.println();
}
}
}
using 4 for loops
package com.stackoverflow;
import java.util.Scanner;
public class Pyramid {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the pyramid limit value: ");
int limit = in.nextInt();
in.close();
for (int i = 0; i < limit; i++) {
for(int j=0; j<limit-i; j++){
System.out.print(" ");
}
for(int j=0; j<=i; j++){
System.out.print(i-j+1);
}
for(int j=i; j>0; j--){
System.out.print(i-j+2);
}
System.out.println();
}
}
}

Can't print the pattern

I created the code that should print a pattern like
12345
2345
345
45
5
I have the code written below, the logic works fine in python but in java the output is different.
class Testing{
public static void main(String args[])
{
for (int i = 1; i<6;i++)
{
for (int j =0; j<i-1;j++)
{
System.out.print(" ");
}
while (i < 6){
System.out.print(k);
System.out.println();
i++;
}
}
}
}
The output is just 12345. I don't understand why does it iterate over first for loop for only once.
Use another variable for while control.
public class Testing {
public static void main(String args[]) {
int k;
for (int i = 1; i < 6; i++) {
for (int j = 0; j < i - 1; j++) {
System.out.print(" ");
}
k = i;
while (k < 6) {
System.out.print(k);
k++;
}
System.out.println();
}
}
}
You can see this in this link
this will show you :
12345
2345
345
45
5
Note: When 'while loop' increases. That increases i value bigger than 6. So next time it terminates the outer loop. That was your mistake.
package com.appointment.api;
class Testing {
public static void main(String args[]) {
for (int i = 1; i < 6; i++) {
System.out.println();
for (int j = 0; j < i - 1; j++) {
System.out.print(" ");
}
int x = i;
while (x < 5) {
System.out.print(i);
x++;
}
}
}
}
Following is a java-8 implementation of the problem:
IntStream.rangeClosed(1, MAX)
.forEach(i -> IntStream.rangeClosed(1, MAX)
.mapToObj(j -> j == MAX ? j + "\n" : j >= i ? j : " ")
.forEach(System.out::print)
);
Set MAX = 5 and it will print your pattern.
Output:
12345
2345
345
45
5

java checkerboard pattern with asterisks

I've looked over lots of posts already and they have helped a lot, but none have covered my issue. I'm trying to print out an alternating checkerboard pattern for a class assignment. My output starting on the first line and every odd line has an extra print at the end. It should be repeating a 8x8 pattern basically. Here is my code and a screenshot of my output.
I need to know how to alter the code so that I only get 8 asterisks in the odd lines instead of the 9 that are showing now.
public class Checkerboard {
public static void main(String[] args) {
int length = 16;
int height = 8;
for (int i = 0; i <= height; i++)
{
if (i % 2 == 0)
{
System.out.print("* ");
}
else
{
System.out.print(" ");
}
for (int j = 0; j <= length; j++)
{
if (j % 2 == 0)
{
System.out.print(" ");
}
else
{
System.out.print("* ");
}
}
System.out.println("");
}
}
}
output
This works for me. I changed the last else statement to an else if with the condition j != length || i % 2 != 0 so now if it is an odd number row it will not print out an extra '*' at the end.
public class mainTest {
public static void main(String[] args) {
int length = 15;
int height = 8;
for (int i = 0; i <= height; i++)
{
if (i % 2 == 0)
{
System.out.print("* ");
}
else
{
System.out.print(" ");
}
for (int j = 0; j <= length; j++)
{
if (j % 2 == 0)
{
System.out.print(" ");
}
else if (j != length || i % 2 != 0)
{
System.out.print("* ");
}
}
System.out.println("");
}
}
}
Although below snippet is not optimized, but it should work for you. There is scope of simplification. Try that.
public static void main(String[] args) {
int length = 16;
int height = 8;
for (int i = 0; i <= height; i++) {
char first = ' ';
char second= '*';
if (i % 2 == 0) {
first = '*';
second = ' ';
}
for (int j = 0; j < length; j++) {
if (j % 2 == 0) {
System.out.print(first);
} else {
System.out.print(second);
}
}
System.out.println("");
}
}

Categories

Resources