I have a Top-level public class with an inner class being created in that same class by creating an instance of the top-level class and then creating an instance of the inner class in that instance of the top-level class.
The issue I’m running into is that after I create the Scanner object and try to run the next() method, is that the program doesn’t allow for the terminal to input anything and then throws an error for there not being a token for it to pick up on.
I have tried using the hasNext() method and using try_catch. For me, the intended behavior is that the Scanner object makes the Thread wait for an input from the terminal.
Here is my code:
import java.util.Scanner;
public class ScannerTest {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.print("ENTER A NUMBER: ");
int inputValue = input.nextInt();
input.close();
System.out.printf("%d multiplied by 5 is equal to %d%n%n", inputValue, inputValue*5);
ScannerTest m = new ScannerTest();
Scanner2 g = m.new Scanner2();
g.gG();
}
private class Scanner2{
public void gG(){
Scanner in = new Scanner(System.in);
System.out.println("Please enter a word: ");
String firstWord = in.next();
in.close();
System.out.println("First word: " + firstWord);
}
}
}
The exception – Exception in thread "main" java.util.NoSuchElementException: No line found – happens when String firstWord = in.next(); is reached. Again, this code is obviously not going to be very useful normally, but I’m trying to experiment with what’s possible.
>Solution :
When you call Scanner.close(), as in your line
input.close();
the Scanner will also close the underlying stream from which it is reading. In your case this closes System.in. So when you are trying to use a Scanner in g.gG() to read from System.in again there is nothing to read because the stream has already been closed. This is why you are getting this exception.
The correct behaviour would be to close System.in when you are done using it, i.e. at the end of the program. However, there is no need to do that since the runtime will close it automatically when the program exits.
PS: on a separate note, if you do want or need to close something you should normally use a try..finally or try-with-resources statement to ensure that the statement is not skipped in the case of exception which could lead to memory or resource leaks.