I am trying to create a program in Java in which the computer randomly guesses a number between 1-100 and allows the user to guess to the number.
If the number is lower
Try this, hope it will help.
public class BinarySearch
{ static Scanner sc = new Scanner(System.in);
public static void main(String a[]) {
int count = 100;
BinarySearch bs = new BinarySearch();
int[] inputArr = bs.takeInputsInCount(count);
System.out
.println("For every question, press Enter if answer is YES, else you can press any other key");
System.out
.println("Think of a number between 1 to 100, press Enter to continue");
String input = sc.nextLine();
if (input.isEmpty()) {
int element = bs.getElementByBinarySearch(inputArr, count);
System.out.println("Your number is : " + element);
} else {
System.out.println("exiting... ");
}
}
private int getElementByBinarySearch(int[] arr, int len) {
int first = 0;
int last = len - 1;
if (isEqual(arr[first]))
return arr[first];
if (isEqual(arr[last]))
return arr[last];
while (last > first) {
int middle = (first + last) / 2;
if (isEqual(arr[middle]))
return arr[middle];
if (isGreater(arr[middle])) {
first = middle + 1;
if (isEqual(arr[first]))
return arr[first];
} else {
last = middle - 1;
if (isEqual(arr[last]))
return arr[last];
}
}
return 0;
}
private boolean isEqual(int m) {
Boolean equalFlag = false;
System.out.println("Is your number :" + m + " ?");
String input = sc.nextLine();
if (input.isEmpty()) {
equalFlag = true;
}
return equalFlag;
}
private boolean isGreater(int m) {
Boolean equalFlag = false;
System.out.println("Is your number greater than :" + m + " ? ");
String input = sc.nextLine();
if (input.isEmpty()) {
equalFlag = true;
}
return equalFlag;
}
private int[] takeInputsInCount(int count) {
int length = count;
int tempArray[] = new int[length];
for (int i = 0; i < length; i++) {
try {
tempArray[i] = i + 1;
} catch (Exception e) {
break;
}
}
return tempArray;
}}