P
P
PRAIT2019-07-09 04:20:38
Java
PRAIT, 2019-07-09 04:20:38

I need to draw an empty square with a cross using cycles, is my solution correct?

Hello everyone who visits! There is a task: Draw a square of this type:
5d23ebbebbdd7686942662.png
Here is what I got in the form of code:

import java.util.Scanner;

public class Kvadrat {

  public static void main(String[] args) {
    try (Scanner sc = new Scanner(System.in)) {
    int count = 11;
      for (int i = 0; i < count; i++) {
        for (int j = 0; j < count; j++) {
          if (i == 0 || i == count - 1 || j == 0 || j == count - 1) {
            System.out.print("*");
          } else if (i == j || j == count - 1 - i){
            System.out.print("*");
          } else {
            System.out.print(" ");
          }
        }
        System.out.println(" ");
      }
    }
  }
}

The fact is that for me the task was not easy, and I really had to think about how to do it. I would be grateful if someone checks the correctness of the solution! Thanks!!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Antony, 2019-07-09
@PRAIT

If you run - this program draws what you need, for any value of count (that is, it obviously works).
According to the code, a couple of words:
1. Do not use transliteration in the names of classes / variables, etc. It is customary to call everything in English.
2. I think any IDE will tell you this for me - you declared Scanner sc, but you don't use it anywhere. I understand that you will most likely add an arbitrary size of the square later, but you could remove this from the code for the question so that it does not hurt your eyes (and in general it will be easier for you to debug a specific functionality when you do not have extra functionality).
3. As Dmitry Shitskov already told you , ifs can be replaced with one like this:

if (i == 0 || i == count - 1 || j == 0 || j == count - 1 || i == j || j == count - 1 - i) {
  System.out.print("*");
} else {
  System.out.print(" ");
}

Although personally I would (to the detriment of the compactness of the code) do the following:
1. Draw first into an array with characters, into which I would write spaces or asterisks. (and then print it out)
2. Make separate functions for drawing each of the lines (which modifies the array)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question