Advertisement
Guest User

Untitled

a guest
Feb 18th, 2019
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.57 KB | None | 0 0
  1.  
  2. package labexer5a;
  3. import java.util.Scanner;
  4. import java.util.InputMismatchException;
  5. public class LabExer5A {
  6.  
  7. public static void main(String[] args) {
  8. Scanner sc = new Scanner(System.in);
  9. int counter = 0;
  10. int ans = 0;
  11. int num = (int)(Math.random()*50+1);
  12. System.out.println("Correct answer: "+num); //Correct Checker
  13. boolean correct = false;
  14.  
  15. System.out.println("Guess a number from 1 to 50!");
  16. while(!correct){
  17. try{
  18. //System.out.println("Retry Count: "+counter);//retry counter
  19. ans = sc.nextInt();
  20. if(ans > 50){
  21. Exception f = new Exception();
  22. counter++;
  23. throw f;
  24. }else if (ans == num){
  25. System.out.println("You got it in "+counter+" attempts(s)");
  26. correct = true;
  27. }else if (ans > num){
  28. System.out.println("Too high. Try again.");
  29. counter++;
  30. }else if (ans < num){
  31. System.out.println("Too low. Try again.");
  32. counter++;
  33. }
  34. }catch (InputMismatchException e){
  35. sc.next();
  36. System.out.println("Invalid input.");
  37. counter++;
  38. }catch (Exception f){
  39. System.out.println("Out of range.");
  40. System.out.println("Guess a number from 1 to 50!");
  41. counter++;
  42. }
  43. }
  44. }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement