Help with a pattern using nested loops (java)

  • Context: Java 
  • Thread starter Thread starter MarcL
  • Start date Start date
  • Tags Tags
    Java Loops
Click For Summary
SUMMARY

The forum discussion centers on creating a diamond pattern in Java using nested loops. The original code utilized a fixed integer value of 5 for the number of rows, but the user later modified it to accept dynamic input via the Scanner class. The user encountered issues with spacing and loop control when transitioning from a constant to a variable input, leading to confusion about how to simplify the code. Suggestions were made to clarify the logic and reduce unnecessary loops for better efficiency.

PREREQUISITES
  • Java programming fundamentals
  • Understanding of nested loops in Java
  • Experience with user input handling using Scanner
  • Basic knowledge of string manipulation and formatting
NEXT STEPS
  • Refactor the diamond pattern code for improved readability and efficiency
  • Explore Java StringBuilder for better string manipulation
  • Learn about algorithm optimization techniques for nested loops
  • Investigate handling even and odd row inputs for diamond patterns
USEFUL FOR

Java developers, programming students, and anyone interested in mastering nested loops and user input handling in Java.

MarcL
Messages
170
Reaction score
2
Hey so I have to make a pattern in the shape of a diamond as follow:
Code:
  1
 123
12345
 123
  1

So first, I wrote the code without using a variable n as the number of rows ( from an input from the user) but just the constant i = 5 ( I am sorry for the variable names, I made many patterns and this was just trying to get it to work so I didn't mind it as I was going to change everything later)
Code:
public class PatternChose {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int k = 0, h=2, c=0;
          for (int i=1 ; i<=5 ; i++)
           {
            { for (int u=2 ; u >= i ; u--)
                  System.out.print(" ");
                   h--;
             for (int j=1  ; j<= i + k ; j++)
                System.out.print(j);
             for (int w=2 ; w>= i; w--)
                System.out.print(" ");
               
                }
                k++;
                System.out.println();
                if (h<0)
                    break;}
              for (int i =2 ; i>=1 ; i--){
                 { for (int l=3 ; l>+i ; l--)
                     System.out.print(" ");
                    for (int m= 0 ; m <=i - c ; m++)
                      System.out.print( m + 1);
                 }
                 c++;
                 System.out.println();
                 
              }
    }

}

Then, as this gave the output that I first did up there, I tried to do it with a value inputted by a user:

Code:
import java.util.Scanner;public class PatternChose {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int k = 0, h=2, c=0, row=1;
        Scanner userInput = new Scanner(System.in);
        System.out.println("Please input your value");
          int newUserInput = userInput.nextInt();
          for (int i=1 ; i<=newUserInput ; i++)
           {
            { for (int u=newUserInput - row ; u >= i ; u--)
                  System.out.print(" ");
                   h--;
             for (int j=1  ; j<= i + k ; j++)
                System.out.print(j);
             for (int w=2 ; w>= i; w--)
                System.out.print(" ");
               
                }
                k++;
                System.out.println();
                if (h<0)
                    break;}
              for (int i =2 ; i>=1 ; i--){
                 { for (int l=3 ; l>+i ; l--)
                     System.out.print(" ");
                    for (int m= 0 ; m <=i - c ; m++)
                      System.out.print( m + 1);
                 }
                 c++;
                 row++;
                 System.out.println();
                 
              }
    }

}
But, I'm having an issue while trying to use a value from an input. This is because in my first code, I used the space to the left of the numbers to tell when the program to break to then form a lower triangle. However, I do notice a pattern with the space vs. the number of rows but it doesn't seem like I'd be able to code it as the values always change. ( I don't think I'm making very much sense??)

Any pointers of what I should do?
 
Technology news on Phys.org
Code:
import java.util.Scanner;public class PatternChosen {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int rowsForUpperTriangle = 0,  c=1;
        Scanner userInput = new Scanner(System.in);
        System.out.println("Please input your value");
          int newUserInput = userInput.nextInt();
          int h = newUserInput / 2;
          for (int i=1 ; i<=newUserInput ; i++)
           {
            { for (int u=newUserInput / 2 ; u >= i ; u--)
                  System.out.print(" ");
                   h--;
             for (int j=1  ; j<= i + rowsForUpperTriangle ; j++)
                System.out.print(j);
             for (int SpaceToRight=2 ; SpaceToRight>= i; SpaceToRight--)
                System.out.print(" ");
               
                }
            rowsForUpperTriangle++;
                System.out.println();
                if (h<0)
                    break;}
              for (int i =newUserInput / 2 ; i>=1 ; i--){
                 { for (int l=newUserInput / 2 ; l>=i ; l--)
                     System.out.print(" ");
                    for (int m= 1  ; m <= newUserInput - (2 * c) ; m++)
                      System.out.print( m );
                 }
                 c++;
                 System.out.println();
                 
              }
    }

}

Anyone can tell me how I could reduce this code? I know there are shorter way to code a diamond but this is what I got, which is pretty messy for something so simple I think..
 
MarcL said:
Anyone can tell me how I could reduce this code? I know there are shorter way to code a diamond but this is what I got, which is pretty messy for something so simple I think..

Hmmm... that seems like a lot of extra loops and processing. Before changing your code, maybe write down in words what you are trying to accomplish.

It looks like for an input of 5, your desired output is 5 lines each with 5 characters (either spaces or integers)...how many (outer) loops would you expect to need to write 5 lines one at a time? How many (inner) loops would you expect to need to write 5 characters one at a time?
How do things change for an even input (number of rows) like 4?
 

Similar threads

  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 19 ·
Replies
19
Views
3K
  • · Replies 1 ·
Replies
1
Views
1K
Replies
8
Views
3K
Replies
1
Views
8K
  • · Replies 3 ·
Replies
3
Views
3K
Replies
4
Views
3K
Replies
2
Views
3K
  • · Replies 1 ·
Replies
1
Views
3K