The Hacker
The Hacker

Reputation: 63

Using a for loop to output a rectangle made of character X

I am having difficulty as to what the for loop should look like. Below is the the desired output:

Enter a number > 10

X X X X X X X X X X

X                 X

X                 X

X                 X

X                 X

X                 X

X                 X

X                 X

X                 X

X X X X X X X X X X

My current code is:

import java.util.*;//imports the utilities
public class RepeatAfterMe {
    public static void main(String[] args) {
        System.out.println("Enter a number ");//Prompt for input
        Scanner kb= new Scanner (System.in);
        int num =kb.nextInt();
        for (int x =0;x<num;x++){//repeats the word
            System.out.println("x");
        }
    }
}

Upvotes: 0

Views: 1048

Answers (3)

Neeraj Jain
Neeraj Jain

Reputation: 7730

Try this out , I have tested on my end .

for(int i=0;i<num;i++)
{
   for(int j=0;j<num;j++)
   {
    if(i==0 || i==num-1)
        System.out.print("X ");
    else
    {
        if(j==0 ||  j==num-1)
            System.out.print("X ");
        else
            System.out.print("  ");//two spaces to achieve your desired output
    }

  } 
    System.out.println();
    System.out.println();
}

Output

X X X X X X X X X X 

X                 X 

X                 X 

X                 X 

X                 X 

X                 X 

X                 X 

X                 X 

X                 X 

X X X X X X X X X X 

Upvotes: 0

javac
javac

Reputation: 2441

This example reads a number from the console and prints the desired output.

EDIT: Changed code because of altered circumstances

import java.util.*;

public class Main {

public static void main(String... args) {
    Scanner scanner = new Scanner(System.in);
    int number = scanner.nextInt(); // Read the number from the console

    // First line
    for (int i = 0; i < number; i++)
        System.out.print("X");
    System.out.println();

    // Middle lines
    for (int i = 0; i < number - 2; i++) {
        System.out.print("X");
        for (int j = 0; j < number - 2; j++) {
            System.out.print(" ");
        }
        System.out.print("X\n");
    }

    // Last line
    for (int i = 0; i < number; i++)
        System.out.print("X");
    System.out.println();

    scanner.close();
}
}

Upvotes: 0

GeorgeG
GeorgeG

Reputation: 362

The following for loop will print the output you provided. However, I am not sure that this is what you wanted

EDITED

    for (int i=0; i<num;i++){
        if (i==0 || i == num-1) {
            for (int j=0;j<num;j++){
                System.out.print("X");
            }
            System.out.println();
        }
        else {
            System.out.print("X");
            for (int j=1;j<num-1;j++){
                System.out.print(" ");
            }
            System.out.println("X");
        }
    }

Upvotes: 1

Related Questions