Hello, at the time of writing one program, a question arose, which I did not like. When creating an array of squares knocks an error, what's the matter?

public class Main { public static void main(String[] args) { Scanner sc; int n; System.out.print("Введіть кількість квадратів: "); while (true) { sc = new Scanner(System.in); if (!sc.hasNextInt()) { System.out.print("Некоректний тип введеного числа! Повторіть спробу: "); } else { n = sc.nextInt(); sc.close(); return; } } // вс, что здесь пишу unreachable statement } } 
  • unreachble statement - Muscled Boy
  • 2
    can replace retrun with break ? - pavel
  • Why create a new Scanner every time? - Igor Fedorov

1 answer 1

Use the break keyword to exit early, rather than return , which in turn terminates the current method , and everything else after return is considered an unreachable unreachable code .

Well, with an array try this:

 Quadrate[] quadrates = new Quadrate[n]; for(int i = 0; i< n; i++) quadrates[i] = new Quadrate(..); 
  • I tried it from the beginning - Muscled Boy
  • @MuscledBoy throw the full code - dirkgntly
  • @MuscledBoy updated the answer - dirkgntly
  • it was a break. and why it was necessary to write it. After all, break is used to complete the execution of the loop, and return returns control after the execution of the method? - Muscled Boy
  • or is it because the cycle. so to speak - eternal - Muscled Boy