Skip to content

Instantly share code, notes, and snippets.

@cassiusvm
Last active April 23, 2021 18:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cassiusvm/9879f7021812bd25fc5cbf93a0988d03 to your computer and use it in GitHub Desktop.
Save cassiusvm/9879f7021812bd25fc5cbf93a0988d03 to your computer and use it in GitHub Desktop.
Scan string and int from standard input
import java.io.Console;
import java.util.Scanner;
public class App {
public void perform() {
firstScanner();
secondScanner();
}
public void firstScanner() {
String str = "";
Console con = System.console();
if (con != null) {
try (Scanner sc = new Scanner(con.reader())) {
System.out.println("Enter a string: ");
if (sc.hasNext()) {
str = sc.next();
sc.nextLine();
}
System.out.println("str = " + str);
} catch (Exception e) {
System.out.println("Exception message: " + e.getMessage());
}
} else {
System.out.println("System console not available");
}
}
public void secondScanner() {
int num = 0;
Console con = System.console();
if (con != null) {
try (Scanner sc = new Scanner(con.reader())) {
System.out.println("Enter a number: ");
if (sc.hasNextInt()) {
num = sc.nextInt();
sc.nextLine();
}
System.out.println("num = " + num);
} catch (Exception e) {
System.out.println("Exception message: " + e.getMessage());
}
} else {
System.out.println("System console not available");
}
}
public static void main(String[] args) {
App app = new App();
app.perform();
System.exit(0);
}
}
@abdorah
Copy link

abdorah commented Apr 23, 2021

thank you man for this gist it helped me a lot to solve a closed System.in problem. I was really astonished when I found out after a hard work that if System.in, a BufferedInputStream from the keyboard, is closed, as happens when the Scanner object is closed, you are closing a System stream that cannot be re-opened.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment