What does scanner.close() do?

Yes, it does mean that System.in will be closed. Test case: import java.util.*; public class CloseScanner { public static void main(String[] args) throws Exception { Scanner scanner = new Scanner(System.in); scanner.close(); System.in.read(); } } This code terminates with $ java CloseScanner Exception in thread “main” java.io.IOException: Stream closed at java.io.BufferedInputStream.getBufIfOpen(BufferedInputStream.java:162) at java.io.BufferedInputStream.fill(BufferedInputStream.java:206) at java.io.BufferedInputStream.read(BufferedInputStream.java:254) at … Read more

java.util.scanner throws NoSuchElementException when application is started with gradle run

You must wire up default stdin to gradle, put this in build.gradle: run { standardInput = System.in } UPDATE: 9 Sep 2021 As suggested by nickbdyer in the comments run gradlew run with –console plain option to avoid all those noisy and irritating prompts Example gradlew –console plain run And if you also want to … Read more

how to take user input in Array using java?

Here’s a simple code that reads strings from stdin, adds them into List<String>, and then uses toArray to convert it to String[] (if you really need to work with arrays). import java.util.*; public class UserInput { public static void main(String[] args) { List<String> list = new ArrayList<String>(); Scanner stdin = new Scanner(System.in); do { System.out.println(“Current … Read more

How to interrupt java.util.Scanner nextLine call

This article describes an approach to avoiding blocking when reading. It gives the code snippet, which you could amend as I indicate in a comment. import java.io.*; import java.util.concurrent.Callable; public class ConsoleInputReadTask implements Callable<String> { public String call() throws IOException { BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); System.out.println(“ConsoleInputReadTask run() called.”); String input; do { … Read more

Is there an equivalent to the Scanner class in C# for strings?

I’m going to add this as a separate answer because it’s quite distinct from the answer I already gave. Here’s how you could start creating your own Scanner class: class Scanner : System.IO.StringReader { string currentWord; public Scanner(string source) : base(source) { readNextWord(); } private void readNextWord() { System.Text.StringBuilder sb = new StringBuilder(); char nextChar; … Read more