0

I'm making a simple project for my high school and I have encountered a problem. The problem is I'm trying to get input with a scanner and check if it is an int or not. But the scanner is not working. Meanwhile I want to run a loop based on user input so for that I need an another scanner.

I have searched online and couldn't really find a solution. I added another scanner, but it is a temporary solution and doesn't work like a proper scanner should do.

System.out.println("please enter a coordinate for X between 1 and " + (forest.getForest().length - 2
  + " if you pick an invalid coordinate a random one will be selected, however it may not have a tree there"));
if (scan.hasNextInt() == false) {
  System.out.println("the coordinate you entered is invalid a random one is being generated");
  x = (int) Math.random() * (forest.getForest().length - 3) + 1;
} else {
  x = scan.nextInt();
  if (x < 1 || x > forest.getForest().length - 2) {
    System.out.println("the coordinate you entered is invalid a random one is being generated");
    x = (int) Math.random() * (forest.getForest().length - 3) + 1;
  }
}

System.out.println("please enter a coordinate for Y between 1 and " + (forest.getForest().length - 2
  + " if you pick an invalid coordinate a random one will be selected, however it may not have a tree there"));
if (scan2.hasNextInt() == false) {
  System.out.println("the coordinate you entered is invalid a random one is being generated");
  y = (int) Math.random() * (forest.getForest().length - 3) + 1;
} else {
  y = scan2.nextInt();
  if (y < 1 || y > forest.getForest().length - 2) {
    System.out.println("the coordinate you entered is invalid a random one is being generated");
    y = (int) Math.random() * (forest.getForest().length - 3) + 1;
  }
}

This is the part of the code that uses the scanners but when I try to get another input, it doesn't work. I don't get any error but it doesn't accept any input.

Jan
  • 2,744
  • 2
  • 18
  • 25
Mrmuawa
  • 1
  • 2
  • Does it only fail after you've entered bad input to the first prompt? If `haveNextInt()` returns `false`, you need to throw away the bad input by calling `nextLine()`, or else any following scanner calls will keep trying to process the same bad input without letting the user enter anything. – Kevin Anderson Jun 08 '19 at 09:38
  • @kevinAnderson it happens in both scenarios – Mrmuawa Jun 08 '19 at 09:44
  • I marked your question as duplicate of other questions about same subject. If you don't believe that solutions from those questions apply to your problem explain your problem farther. Use [edit] option to do so. Also just like you don't only tell a doctor "I am sick", you should avoid tell ["doesn't work"](https://web.archive.org/web/20180124130721/http://importblogkit.com/2015/07/does-not-work/) while asking about technical problem. – Pshemo Jun 08 '19 at 17:53

0 Answers0