Advertisement
Guest User

Untitled

a guest
Aug 19th, 2019
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. import javax.swing.*;
  2. import java.util.Random;
  3.  
  4. class GuessGame {
  5. private double bestScore;
  6. private Random rnd = new Random();
  7.  
  8. public void play(int max) {
  9. int secret = rnd.nextInt(max);
  10.  
  11. int count = 0;
  12. boolean guessed = false;
  13.  
  14. while (!guessed) {
  15. count++;
  16. int userInput = getUserInput();
  17.  
  18. if (userInput == secret) {
  19. double score = calcScore(max, count);
  20. saveResult(score);
  21. JOptionPane.showMessageDialog(null, "Yohoo, your score: " + score);
  22. guessed = true;
  23. } else {
  24.  
  25. if (userInput >= secret)
  26. JOptionPane.showMessageDialog(null, "Lesser");
  27. else
  28. JOptionPane.showMessageDialog(null, "Greater");
  29. }
  30.  
  31. }
  32. }
  33.  
  34. private int getUserInput() {
  35. while (true){
  36. try {
  37. return Integer.parseInt(JOptionPane.showInputDialog("Guess number"));
  38. }
  39. catch (Throwable throwable){
  40. JOptionPane.showMessageDialog(null, "Oops, pls input number");
  41. }
  42. }
  43. }
  44.  
  45. private double calcScore(int max,int count){
  46. return max / (float)count;
  47. }
  48.  
  49. private void saveResult(double score) {
  50. bestScore = Math.max(score, bestScore);
  51. }
  52.  
  53. double getBestScore() {
  54. return bestScore;
  55. }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement