Pergunta

I'm trying to create a square made from a user inputted character and made from the dimension they so choose.

public class Square
{
  public static void main(String[] args)
  {
    final byte MIN_SIZE =  2,
           MAX_SIZE = 20;

    byte size;
    char fill;

    Scanner input = new Scanner(System.in);

    do
    {
      System.out.printf("Enter the size of the square (%d-%d): ",
                        MIN_SIZE, MAX_SIZE);
      size = (byte)input.nextLong();
    } while (size > MAX_SIZE || size < MIN_SIZE);
    System.out.print("Enter the fill character: ");
    fill = input.next().charAt(0);

    //This is where the code which outputs the square would be//

  }
}

An example of what the square should look like is as follows: If the size is 5 and the fill is "@"

@@@@@
@@@@@
@@@@@
@@@@@
@@@@@
Foi útil?

Solução

You shouldn't ask for a nextLong and save it in a byte. The size var should be a long.

To print the square you can neast to simple fors

long i,j;

for(i = 0; i < size; i++)
{
    for(j = 0; j < size; j++)
        System.out.print(fill);

    System.out.println();
}

You could make it perform better, creating a string containing the entire line with the fill character, and then print it the number of rows there are, but for MAX_SIZE = 20 that will do.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top