Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2014
213
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.29 KB | None | 0 0
  1. import java.util.InputMismatchException;
  2. import java.util.Scanner;
  3.  
  4. public class ConsoleReader {
  5.  
  6. Scanner reader;
  7.  
  8. public ConsoleReader() {
  9. reader = new Scanner(System.in);
  10. //reader.useDelimiter(System.getProperty("line.separator"));
  11. }
  12.  
  13. public int readInt(String msg) {
  14. int num = 0;
  15. boolean loop = true;
  16.  
  17. while (loop) {
  18. try {
  19. System.out.println(msg);
  20. num = reader.nextInt();
  21.  
  22. loop = false;
  23. } catch (InputMismatchException e) {
  24. System.out.println("Invalid value!");
  25.  
  26. }
  27. }
  28. return num;
  29. }
  30.  
  31. }
  32.  
  33. ...
  34. } catch (InputMismatchException e) {
  35. System.out.println("Invalid value!");
  36. reader.next(); // this consumes the invalid token
  37. }
  38.  
  39. String line = reader.nextLine();
  40. Scanner sc = new Scanner(line);
  41.  
  42. public int readInt(String msg) {
  43. int num = 0;
  44. boolean loop = true;
  45.  
  46. while (loop) {
  47. try {
  48. System.out.println(msg);
  49. String line = reader.nextLine();
  50. Scanner sc = new Scanner(line);
  51. num = sc.nextInt();
  52. loop = false;
  53. } catch (InputMismatchException e) {
  54. System.out.println("Invalid value!");
  55.  
  56. }
  57. }
  58. return num;
  59. }
  60.  
  61. public int readInt(String msg) {
  62. int num = 0;
  63. try {
  64. System.out.println(msg);
  65. num = (new Scanner(System.in)).nextInt();
  66. } catch (InputMismatchException e) {
  67. System.out.println("Invalid value!");
  68. num = readInt(msg);
  69. }
  70. return num;
  71. }
  72.  
  73. package nzt.nazakthul.app;
  74.  
  75. import java.util.*;
  76.  
  77. public class NztMainApp {
  78.  
  79. public static void main(String[] args) {
  80. ReadNumber readObj = new ReadNumber();
  81. readObj.readNumber();
  82. }
  83.  
  84. }
  85.  
  86. class ReadNumber {
  87. int no;
  88.  
  89. int readNumber() {
  90. Scanner number = new Scanner(System.in);
  91. int no=0;
  92. boolean b=true;
  93. do {
  94.  
  95. try {
  96. System.out.print("Enter a number:t");
  97. no = number.nextInt();
  98. } catch (InputMismatchException e) {
  99. System.out.println("No Number");
  100. //e.printStackTrace();
  101.  
  102. b=false;
  103. }
  104.  
  105. }
  106.  
  107. while (b);
  108. return no;
  109.  
  110. }
  111.  
  112. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement