Home > database >  Creating a number rectangle in Java using a nested for loop with one number input
Creating a number rectangle in Java using a nested for loop with one number input

Time:09-23

I'm new to Java and have an assignment that requires me to create a rectangle of numbers where the numbers start from the 'user input' number and reduce to 1 in the middle (See example). I've created a very simplified code that can do it, but I would have to create an 'else if' for each number up to the 'user input' number. Obviously, there is a way to repeat the code using some variable, but I can't seem to figure out how to do it. Can I get some help? Here is the code I am at right now:

import java.util.Scanner;

public class Assign {

public static void main(String[] args) {
    
    Scanner scan = new Scanner(System.in);
    
    System.out.println("Select rectangle size:");
    int user = scan.nextInt();
    
    for (int row = 1; row <= ((user*2)-1); row  ) {
        for (int col = 1; col <= ((user*2)-1); col   ) {
            if ((row == 1) || (col == 1) || (row == (user*2)-1) || (col == (user*2)-1)) {
                System.out.printf("-",user);
            }else if ((col == (2)) || col == (user*2)-(2) || row == 2 || row == (user*2)-(2)) {
                System.out.printf("-",user - (1));
            }else if ((col == (3)) || col == (user*2)-(3) || row == 3 || row == (user*2)-(3)) {
                System.out.printf("-",user - (2));
            }else if ((col == (4)) || col == (user*2)-(4) || row == 4 || row == (user*2)-(4)) {
                System.out.printf("-",user - (3));
            }else if ((col == (5)) || col == (user*2)-(5) || row == 5 || row == (user*2)-(5)) {
                System.out.printf("-",user - (4));
            }
        } 
        System.out.println();
    }
    input.close();

}

}

CodePudding user response:

I have a solution for this problem. I hope It can help you.

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    System.out.println("Please select your max number:");
    int userChoice = input.nextInt();
    int end = userChoice * 2 - 1;
    int decrement = 0;
    int increment = 0;

    for (int i = 0; i < end; i  ) {
        for (int j = 0; j < end; j  ) {
            if(end - i - 1 < j) {
                increment  ;
            }
            System.out.print(userChoice - decrement   increment);
            if(decrement < i) {
                decrement  ;
            }

        }
        decrement = 0;
        increment = 0;
        System.out.println();
    }
    input.close();

}
  • Related