Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.InputMismatchException;
- import java.util.Scanner;
- public class ConsoleReader {
- Scanner reader;
- public ConsoleReader() {
- reader = new Scanner(System.in);
- //reader.useDelimiter(System.getProperty("line.separator"));
- }
- public int readInt(String msg) {
- int num = 0;
- boolean loop = true;
- while (loop) {
- try {
- System.out.println(msg);
- num = reader.nextInt();
- loop = false;
- } catch (InputMismatchException e) {
- System.out.println("Invalid value!");
- }
- }
- return num;
- }
- }
- ...
- } catch (InputMismatchException e) {
- System.out.println("Invalid value!");
- reader.next(); // this consumes the invalid token
- }
- String line = reader.nextLine();
- Scanner sc = new Scanner(line);
- public int readInt(String msg) {
- int num = 0;
- boolean loop = true;
- while (loop) {
- try {
- System.out.println(msg);
- String line = reader.nextLine();
- Scanner sc = new Scanner(line);
- num = sc.nextInt();
- loop = false;
- } catch (InputMismatchException e) {
- System.out.println("Invalid value!");
- }
- }
- return num;
- }
- public int readInt(String msg) {
- int num = 0;
- try {
- System.out.println(msg);
- num = (new Scanner(System.in)).nextInt();
- } catch (InputMismatchException e) {
- System.out.println("Invalid value!");
- num = readInt(msg);
- }
- return num;
- }
- package nzt.nazakthul.app;
- import java.util.*;
- public class NztMainApp {
- public static void main(String[] args) {
- ReadNumber readObj = new ReadNumber();
- readObj.readNumber();
- }
- }
- class ReadNumber {
- int no;
- int readNumber() {
- Scanner number = new Scanner(System.in);
- int no=0;
- boolean b=true;
- do {
- try {
- System.out.print("Enter a number:t");
- no = number.nextInt();
- } catch (InputMismatchException e) {
- System.out.println("No Number");
- //e.printStackTrace();
- b=false;
- }
- }
- while (b);
- return no;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement