Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.