Write a program that plays a guessing game where the computertries to guess a nu
ID: 3612079 • Letter: W
Question
Write a program that plays a guessing game where the computertries to guess a number picked by the user. The program asksthe user to think of a secret number and then asks the user asequence of guesses. After each guess the user must reportwhether it is too high, or too low, or correct. The programshould count the number of guesses. (hint: Maintain HighestPossibleand LowestPossible variables and always guess midway between thetwo. This is called a binary search.)
The Program should look similar to:
Think of a number between 1 and 100 andthe press enter
Is the number 50(C-correct,L-low, H-High) H
Is the number25(C-correct, L-low, H-High) H
Is the number 13(C-correct,L-low, H-High) L
Is the number 19(C-correct,L-low, H-High) C
It took you 4 guesses.
Do you want to play again?n
Thanks for using Herndonproductions
Explanation / Answer
please rate - thanks importjavax.swing.*;import java.lang.*;
import java.util.*;
public class binarysearchJOption
{ public static void main( String [] args )
{ Scanner in= newScanner(System.in);
intmid,max,min,guesses;
String ans;
char c;
boolean good,done;
do
{done=false;
min=1;
max=100;
guesses=0;
JOptionPane.showMessageDialog(null,"Pick anumber between "+min+" and "+max+" and then press enter ");
do
{mid=(min+max)/2;
ans =JOptionPane.showInputDialog(null, "Is the number"+mid+"(C-correct,L-low,H-high)");
c = ans.charAt(0);
guesses++;
good=true;
switch(c)
{default:good=false;
guesses--;
JOptionPane.showMessageDialog(null,"Illegal input ");
break;
case 'H':
case 'h': max=mid-1;
break;
case 'L':
case 'l': min=mid+1;
break;
case 'C':
case 'c': done=true;
ans =JOptionPane.showInputDialog(null, "It took you "+guesses+"guesses Do you want to play again(Y/N)");
c = ans.charAt(0);
if(c!='Y'&&c!='y')
{JOptionPane.showMessageDialog(null,"Thanks for using Herndonproductions");
System.exit(0);
}
}
}while(!done);
}while(true);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.