repl.it
Java

java

fork
loading
Files
  • Main.java
  • jdt.ls-java-project
  • numberGuesser.java
Main.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import java.util.Scanner;

public class Main {
  public static boolean playAgain(){
    System.out.print("Ok, would you like to play again? (y/n): ");
    char response = new Scanner(System.in).nextLine().charAt(0);
    return response == 'y';

}
public static void playGame(){
  System.out.println("Think of a number between 1 and 100.");
  int low = 1;
  int high = 100;
  boolean found = false;
  while(!found){
    int mid = getMidpoint(low, high);
    char userResponse = getUserResponseToGuess(mid);
    if (userResponse == 'c'){
      return;
      }
      else if (userResponse == 'h'){
        low = mid + 1;
        }
        else if (userResponse == 'l'){
          high = mid - 1;
          }
          else {
            System.out.printf("You may only answer with the following letters (h/l/c)");
            }
            }
            }
            public static int getMidpoint(int low, int high){
              if ((low + high) % 2 == 0)
              return (low + high) / 2;
              else
              return (low + high - 1) / 2;
              }
              public static char getUserResponseToGuess(int mid){
                System.out.print("Is it " + mid +" (h/l/c): ");
                char response = new Scanner(System.in).nextLine().charAt(0);
                return response;
                }
                public static void main(String[] args) {
                  do{
                    playOneGame();
                    }while(shouldPlayAgain());
                    }
                    }