Hello, there was a question: for example, created a stream

Scanner sc = new Scanner(System.in); 

I will write in the code after that sc.close (); so that he does not use resources. In this case, if necessary, I can then create a stream with the same name, after closing, because it is deleted? For example, the following code:

 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(); break; } } Quadrate[] quadrates = new Quadrate[n]; for(int i = 0; i < quadrates.length; i++) { System.out.printf("Введіть сторону %d + 1 - го: ", i); double v = sc.doubleNextInt(); quadrates[i] = new Quadrate(v); } } } 

How to implement this code correctly?

  • one
    There is no need to create a new Scanner on each pass of the cycle. Create one before the loop. - Nofate
  • Help. please, very necessary - Muscled Boy
  • @ Nofate, that is, each sc value will simply be replaced by a new one? - Muscled Boy
  • one
    Not. There will be just one sc value. - Nofate
  • 2
    specifically, in this case it is better not to close at all, since scanner.close() will close System.in at the same time, after which the new scanners will no longer be able to read anything from there. Well, to recreate the scanner, really, each time is not necessary, one copy at the beginning of the method is enough. - zRrr

1 answer 1

Take out the creation of the Scanner at the beginning of the program and use one copy. Call sc.close(); in your case there is no need, because this will close the input stream you are reading from.

 public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n; System.out.print("Введіть кількість квадратів: "); while (true) { if (!sc.hasNextInt()) { System.out.print("Некоректний тип введеного числа! Повторіть спробу: "); sc.next() } else { n = sc.nextInt(); break; } } Quadrate[] quadrates = new Quadrate[n]; for(int i = 0; i < quadrates.length; i++) { System.out.printf("Введіть сторону %d + 1 - го: ", i); double v = sc.nextDouble(); quadrates[i] = new Quadrate(v); } } } 
  • I understood, thank you, but there is a new problem: except for integers, it is not possible to enter the real side - Muscled Boy
  • @MuscledBoy, not sure what the problem is. - Nofate
  • for a start I will ask you what the poprovka you made does. We check if the integer is entered, if not, then we write, "Uncorrected ..." and what are we doing here? - Muscled Boy
  • return the next token? - Muscled Boy
  • and what is a token in general? - Muscled Boy