?
Solved

Simple application

Posted on 2001-06-27
13
Medium Priority
?
196 Views
Last Modified: 2013-11-23
I need a very simple program.

What I want is an application (kind of executable jar file which can be initiated by double clicking).

There will be three buttons. "Higher", "Lower", "This is it".

The user picks a number in a range of 1-100 and let the computer guess it.
If the computer guesses it, game is over.

There will be one more button...."Play Again".

If user enters a number above 100, a message should be displayed.
If possible, the program should also display the number of tries computer took to guess the number.

0
Comment
Question by:desisant
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 2
  • 2
  • +5
13 Comments
 
LVL 28

Expert Comment

by:rrz
ID: 6233771
There is a program very similar to what you describe.
It is distributed as an example JSP page with Tomcat 3.2
0
 
LVL 1

Expert Comment

by:shahnazali
ID: 6233962
This is a doubt or ur home assignment ?
0
 

Author Comment

by:desisant
ID: 6234040
Its sort of assignment . My friend asked me to do this.Its not a school assignment.
I want the code in a frame and not in a servlet.
Please can anyone help me?
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 2

Expert Comment

by:k_suchdeva
ID: 6234369
How we will tell to the computer that the actual number is higher/lower than the guessed number ??
It is not possible through Buttons.
0
 
LVL 1

Expert Comment

by:ccaprar
ID: 6234566
Didn't you mean the computer picks a number and the user tries to guess it?
0
 
LVL 2

Expert Comment

by:k_suchdeva
ID: 6234578
Yes that's what it should do.
0
 
LVL 15

Expert Comment

by:mohan_sekar
ID: 6234617
Hi desisant,

         What is the purpose of the 3 buttons. Please be clear in your doubts.

0
 
LVL 15

Accepted Solution

by:
ozymandias earned 1200 total points
ID: 6234773
Here is the code for the application.
Save it as GuessingGame.java and compile.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;

public class GuessingGame extends JFrame{

      private int target = 0;
      private int guessCount = 0;
      private int lbound = 1;
      private int ubound = 100;

      Container contentPane;
      JTextField targetField;
      JLabel targetLabel;
      JTextField guessField;
      JLabel guessLabel;
      JButton      btnHigher;
      JButton      btnLower;
      JButton      btnHit;
      JButton btnStart;
      JButton btnAuto;

      public GuessingGame(String args[]){
            super("GuessingGame");
            this.setResizable(false);
            this.setDefaultCloseOperation(EXIT_ON_CLOSE);
            contentPane = this.getContentPane();
            contentPane.setLayout(new FlowLayout());
            targetField = new JTextField(12);
            targetLabel = new JLabel("Target");
            guessField = new JTextField(12);
            guessLabel = new JLabel("Guess");
            contentPane.add(targetLabel);
            contentPane.add(targetField);
            guessField.setEditable(false);
            contentPane.add(guessLabel);
            contentPane.add(guessField);
            btnStart = new JButton("Start");
            btnLower = new JButton("Lower");
            btnHit = new JButton("That's It !");
            btnHigher = new JButton("Higher");
            btnAuto = new JButton("Auto");

            btnStart.addActionListener(new ActionListener(){
                  public void actionPerformed (ActionEvent ae){
                        newGame(false);
                  }
            });

            btnLower.addActionListener(new ActionListener(){
                  public void actionPerformed (ActionEvent ae){
                        try{
                              setUBound(guessField.getText());
                        }catch(NumberFormatException nfe){
                              return;
                        }
                        guess();
                  }
            });

            btnHit.addActionListener(new ActionListener(){
                  public void actionPerformed (ActionEvent ae){
                        JOptionPane.showMessageDialog(null,"Ha, ha ! Got you in " + guessCount + " guesses.");
                        guessField.setText("");
                        targetField.setText("");
                        btnHigher.setEnabled(false);
                        btnLower.setEnabled(false);
                        btnHit.setEnabled(false);
                  }
            });

            btnHigher.addActionListener(new ActionListener(){
                  public void actionPerformed (ActionEvent ae){
                        try{
                              setLBound(guessField.getText());
                        }catch(NumberFormatException nfe){
                              return;
                        }
                        guess();
                  }
            });

            btnAuto.addActionListener(new ActionListener(){
                  public void actionPerformed (ActionEvent ae){
                        guessCountAverage(100);
                  }
            });


            contentPane.add(btnStart);
            contentPane.add(btnLower);
            contentPane.add(btnHit);
            contentPane.add(btnHigher);
            contentPane.add(btnAuto);
            btnHigher.setEnabled(false);
            btnLower.setEnabled(false);
            btnHit.setEnabled(false);
      }

      public static void main(String args[]){
            GuessingGame gg = new GuessingGame(args);
            gg.setSize(400,100);
            gg.setVisible(true);
      }

      private void guess(){
            Integer guess;
            guess = new Integer((int)(Math.floor(Math.random() * (ubound - lbound)) + lbound));
            guessCount++;
            guessField.setText(guess.toString());
      }

      private void newGame(boolean auto){
            guessCount = 0;
            lbound = 1;
            ubound = 100;
            try{
                  setTarget(targetField.getText());
            }catch(NumberFormatException nfe){
                  JOptionPane.showMessageDialog(this,"Target number must be an integer between 1 and 100.");
                  return;
            }
            if (!auto){
                  btnHigher.setEnabled(true);
                  btnLower.setEnabled(true);
                  btnHit.setEnabled(true);
            }
            guess();
      }

      private void setTarget(String s) throws NumberFormatException{
            int t = Integer.parseInt(s);
            if (t < 1 || t > 100){
                  throw new NumberFormatException();
            }else{
                  target = t;
            }
      }

      private void setUBound(String s) throws NumberFormatException{
            int n = Integer.parseInt(s);
            if (n <= target){
                  JOptionPane.showMessageDialog(this,"Are you sure that " + target + " is lower than " + n + " ?");
                  throw new NumberFormatException();
            }else{
                  ubound = n - 1;
            }
      }

      private void setLBound(String s) throws NumberFormatException{
            int n = Integer.parseInt(s);
            if (n >= target){
                  JOptionPane.showMessageDialog(this,"Are you sure that " + target + " is higher than " + n + " ?");
                  throw new NumberFormatException();
            }else{
                  lbound = n + 1;
            }
      }

      private int playGame(){
            Integer randomTarget = new Integer((int)(Math.floor(Math.random() * (ubound - lbound)) + lbound));
            targetField.setText(randomTarget.toString());
            setTarget(randomTarget.toString());
            newGame(true);
            while (true){
                  int g = Integer.parseInt(guessField.getText());
                  if (g > target){ubound = g + 1;}
                  if (g < target){lbound = g + 1;}
                  if (g == target){break;}
                  guess();
            }
            return guessCount;
      }

      private void guessCountAverage(int a){
            btnStart.setEnabled(false);
            int guessCountTotal = 0;
            int guessCountMin = 0;
            int guessCountMax = 0;
            for (int i = 0; i < a; i++){
                  int g = playGame();
                  guessCountTotal += g;
                  guessCountMin = (g < guessCountMin || guessCountMin == 0) ? g : guessCountMin;
                  guessCountMax = (g > guessCountMax || guessCountMax == 0) ? g : guessCountMax;
            }
            double average = (double)guessCountTotal / (double)a;
            JOptionPane.showMessageDialog(this,"Games Played : " + a + "\nTotal Guesses : " + guessCountTotal + "\nAverage Number of Guesses : " + Math.round(average) + "\nMinimum Number of Guesses : " + guessCountMin + "\nMaximum Number of Guesses : " + guessCountMax);
            btnStart.setEnabled(true);
      }
}
0
 
LVL 15

Expert Comment

by:ozymandias
ID: 6234783
To create a jar file first save the following as GuessingGame.mf in the same directory as GuessingGame.class created when you compiled GuessingGame.java.

  Manifest-Version: 1.0
  Main-Class: GuessingGame

Then run the following command from that directory :

 jar -cvfm GuessingGame.jar GuessingGame.mf *.class

You should end up with GuessingGame.jar which will run the application when you double-click on it.
0
 
LVL 2

Expert Comment

by:mzimmer74
ID: 6234784
I've seen a program like this before, and it's basically used to show that (if the user doesn't cheat) it is possible to guess a number between 1 and 100 in 7 tries or less.  The algorithm is very simple.  Say User A picks 27 as their number.  The computer runs a binary search on it by constantly picking the midpoint number, starting at 50 (midpoint of 1 and 100).  Here's how this sample would run.

Computer: 50
User: Lower
Computer: 25 (between 1 and 50)
User: Higher
Computer: 37 (25-50)
User: Lower
Computer: 31 (25-37)
User: Lower
Computer: 28 (25-31)
User: Lower
Computer: 26 (25-28)
User: Higher
Computer: 27 (26-28)  **correct**

Total number of guesses is 7.

Hope that clarifies the problem.  I'm sure you'll be able to figure out the logic now.
0
 
LVL 15

Expert Comment

by:ozymandias
ID: 6234795
BTW, I added and extra function just for fun becuase EE was down all day and I was bored.

There is an extra button called Auto.
When clicked the computer will play 100 games against itself and then tell you the average, minimum and maximum number of guesses it took to win over that 100 games.
0
 
LVL 15

Expert Comment

by:ozymandias
ID: 6234903
mzimmer, in the logic I used the computer makes a random guess between lower and upper bounds. The lower and upper bounds start off at 1 and 100. Each time the user responds "lower" the computer resets the upper bound to its last guess and each time the user responds "higher" the computer resets its lower bound to its last guess.

To use your method you just replace this line in the guess method :

  guess = new Integer((int)(Math.floor(Math.random() * (ubound - lbound)) + lbound));

with this line :

  guess = new Integer(lbound + ((ubound-lbound)/2));

Using this method the average number of guesses require by the computer is reduced from 8 to 6, but I like the slightly more random element.

BTW, there is an error in my earlier code in the auto function. The playGame() method should read as follows :

private int playGame(){
    Integer randomTarget = new Integer((int)(Math.floor(Math.random() * (100 - 1)) + 1));
    targetField.setText(randomTarget.toString());
    setTarget(randomTarget.toString());
    newGame(true);
    while (true){
        int g = Integer.parseInt(guessField.getText());
        if (g > target){ubound = g - 1;}
        if (g < target){lbound = g + 1;}
        if (g == target){break;}
        guess();
    }
    return guessCount;
}
0
 

Author Comment

by:desisant
ID: 6236473
Thanks A lot!
0

Featured Post

[Webinar] How Hackers Steal Your Credentials

Do You Know How Hackers Steal Your Credentials? Join us and Skyport Systems to learn how hackers steal your credentials and why Active Directory must be secure to stop them.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
Suggested Courses
Course of the Month8 days, 8 hours left to enroll

764 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question