M
M
Makaron30002021-02-24 14:21:13
Java
Makaron3000, 2021-02-24 14:21:13

Why is the scan is never closed error and the code doesn't work as it should?

The essence of the program is guessing the number that the computer generates on its own, it would seem that everything is written ok, but at startup a window pops up with a saving error, if you just press ok, it prompts you to enter a number, but do not display the number is there lower or higher?
Also in the line "Scanner scan = new Scanner(System.in);" the development environment prompts "scan is never closed"
:

import java.util.Scanner;

public class HiLo {

  public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    // Генерация случайного числа, которое будет угадыват пользователь
    
    int theNumber = (int)(Math.random() * 100 + 1);
    
    //System.out.println(theNumber);
    int guess = 0;
    while (guess != theNumber) {
      System.out.println("Guess a number between 1 and 100:");
          guess = scan.nextInt();
          
          if (guess < theNumber)
          	System.out.println(guess + " is too low. Try again.");
          else if (guess > theNumber)
          	System.out.println(guess + " is too high. Try again.");
          else
          	System.out.println(guess + " is correct. You win!");
    }
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Roo, 2021-02-24
@xez

With code, everything is tip-top. The problem is most likely with your development environment.
scanner can be closed somewhere at the end.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question