Last active
April 23, 2021 18:22
-
-
Save cassiusvm/9879f7021812bd25fc5cbf93a0988d03 to your computer and use it in GitHub Desktop.
Scan string and int from standard input
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.