Advertisement
Guest User

Untitled

a guest
Dec 4th, 2016
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.67 KB | None | 0 0
  1. do{ //Begin of loop
  2. try{ //Try this code
  3. System.out.println("Enter a number");
  4. double i = read.nextDouble(); //Reads user input
  5. double rn = r.nextInt(10); //Generates random number rn
  6. System.out.println(i + " divided by random number " + rn + " is " + (i/rn));
  7. }catch(InputMismatchException type_error){ //Catches error if there is a type mismatch
  8. //Example error: if user enters a letter instead of a double
  9. System.out.println("Error. You cannot divide a letter by a number!");
  10. break; //break stops the execution of the program
  11. }
  12.  
  13. //using a continue statement here does not work
  14. }while(true); //Loop forever
  15.  
  16. Scanner read = new Scanner(System.in);
  17. Random r = new Random();
  18.  
  19. do { //Begin of loop
  20.  
  21. try { //Try this code
  22. System.out.println("Enter a number");
  23. double i = read.nextDouble(); //Reads user input
  24. double rn = r.nextInt(10); //Generates random number rn
  25. System.out.println(i + " divided by random number " + rn + " is " + (i / rn));
  26.  
  27. } catch (InputMismatchException type_error) { //Catches error if there is a type mismatch
  28. //Example error: if user enters a letter instead of a double
  29. System.out.println("Error. You cannot divide a letter by a number!");
  30.  
  31. // Empty the scanner before the next iteration:
  32. read.next();
  33. }
  34.  
  35. //using a continue statement here does not work
  36. } while (true); //Loop forever
  37.  
  38. Scanner read = new Scanner(System.in);
  39. do {
  40. try {
  41. // trimmed out non-necessary stuff
  42. System.out.println("Enter a number");
  43. double i = Double.parseDouble(read.nextLine());
  44. System.out.println(i);
  45. // changed exception caught
  46. }
  47. catch (NumberFormatException type_error) {
  48. System.out.println("Error. You cannot divide a letter by a number!");
  49. continue;
  50. }
  51.  
  52. } while (true);
  53.  
  54. do{ //Begin loop
  55.  
  56. try{ //Try this code
  57. System.out.println("Enter a number");
  58. double i = read.nextDouble(); //Reads user input
  59. double rn = r.nextInt(10); //Generates random number rn
  60. System.out.println(i + " divided by random number " + rn + " is " + (i/rn));
  61.  
  62.  
  63. }catch(InputMismatchException type_error){ //Catches error if there is a type mismatch
  64. //Example error: if user enters a letter instead of a double
  65. System.out.println("Error. You cannot divide " + read.next() + " by a number!");
  66.  
  67. }
  68.  
  69.  
  70.  
  71. } while(true);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement