Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Need to a JAVA program that begins by asking the user to think of, and write dow

ID: 666258 • Letter: N

Question

Need to a JAVA program that begins by asking the user to think of, and write down, a number between 1 and 1,000,000.  

-- THEN it asks questions like "Is it greater than 500000?", and the user answers "Yes" or "yes" or "no or "NO", or "Got It!". Use JOptionPane.showInputDialog to ask questions and get answers. Use something like "answer.toLowerCase().beginsWith("y") to decide what the user asked. Ask these questions in a loop until you have guessed the correct number.

Suggestion: keep two int variables "lo" and "hi", and keep asking about (lo+hi)/2. Allow three answers:

"higher", "lower", or "you guessed it". If you get "you guessed it", you are done. If the answer is higher, adjust "lo" to your new guess. If the answer is lower, adjust "hi" to your guess.

Explanation / Answer

/* I used netbeans ide to create this program */

Program:

import javax.swing.*;

public class JavaApplication4
{
public static void main(String[] args)
{
JFrame frame = new JFrame("Guess a number");
long number;
long GuessedNumber=0;
long hi=1000000,lo=1;
String ans;
// prompt the user to enter the input
number= Integer.parseInt(JOptionPane.showInputDialog(frame, "Enter a number between 1 and 1,000,000"));
while(GuessedNumber!=number)
{
GuessedNumber=(lo+hi)/2;
String q="Is it greater than "+GuessedNumber+"? (Yes / No / Got it)";
// prompt the user to enter comment about guessed number
ans=JOptionPane.showInputDialog(frame,q);
if(ans.toLowerCase().startsWith("y", 0)|| ans.toUpperCase().startsWith("Y", 0))
{
lo=GuessedNumber;
}
else if(ans.toLowerCase().startsWith("n", 0)|| ans.toUpperCase().startsWith("N", 0))
{
hi=GuessedNumber;
}
else if(ans.toLowerCase().startsWith("g", 0)|| ans.toUpperCase().startsWith("G", 0))
{
String r="Hi! You have entered "+GuessedNumber;
JOptionPane.showConfirmDialog(frame,r);
break;
}
}
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote