How would I write a jave program to solve a random guessed number between 1 and
ID: 664899 • Letter: H
Question
How would I write a jave program to solve a random guessed number between 1 and 1000000? I get confused when trying to do a while loop.
while(JOptionPane.showConfirmDialog(null, "Is your number less than or equal to"+(h-((h-l)/2))+"?","warning",option)==JOptionPane.YES_OPTION){
h=(h-((h-l)/2));
l=l;
JOptionPane.showMessageDialog(null, "Low:"+l+" High: "+h);}
//dialogResult=JOptionPane.showConfirmDialog(null, "Is your number less than"+(h-((h-l)/2))+"?","warning",option);
if (JOptionPane.showConfirmDialog(null, "Is your number lesss than or equal to"+(h-((h-l)/2))+"?","warning",option)==JOptionPane.NO_OPTION){
JOptionPane.showMessageDialog(null, "Low:"+l+" High: "+h);
l=(h-((h-l)/2));
h=h;
JOptionPane.showMessageDialog(null, "Low:"+l+" High: "+h);
if(h==l){
JOptionPane.showMessageDialog(null, "Your number is: "+l);
}
This is what I have tried, and it doesn't work. It just ends the loop, but I want it to continue to go back and forth till it gets and answer. Thanks for any ideas
Explanation / Answer
// File: JOptionPaneTest.java
import java.util.Random;
import javax.swing.JOptionPane;
public class JOptionPaneTest
{
public static void main(String[] args)
{
Random rand = new Random();
int randomNumber = 1 + rand.nextInt(100);
System.out.println(randomNumber);
int l = 1;
int h = 100;
int option = JOptionPane.YES_NO_OPTION;
JOptionPane.showMessageDialog(null, "Low: " + l + " High: " + h);
while(true)
{
if(JOptionPane.showConfirmDialog(null,
"Is your number less than "
+ (h - ((h - l) / 2)) + "?", "warning", option) == JOptionPane.YES_OPTION)
{
h = h - ((h - l) / 2);
JOptionPane.showMessageDialog(null, "Low: " + l + " High: " + h);
}
else if(JOptionPane.showConfirmDialog(null, "Is your number greater than " + (h - ((h - l) / 2)) + "?", "warning", option) == JOptionPane.YES_OPTION)
{
l = h - ((h - l) / 2);
JOptionPane.showMessageDialog(null, "Low: " + l + " High: " + h);
}
else
{
JOptionPane.showMessageDialog(null, "Your number is: " + (h - ((h - l) / 2)));
break;
}
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.