Solved

Simple application

Posted on 2001-06-27
13
185 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
  • 4
  • 2
  • 2
  • +5
13 Comments
 
LVL 27

Expert Comment

by:rrz
Comment Utility
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
Comment Utility
This is a doubt or ur home assignment ?
0
 

Author Comment

by:desisant
Comment Utility
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
 
LVL 2

Expert Comment

by:k_suchdeva
Comment Utility
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
Comment Utility
Didn't you mean the computer picks a number and the user tries to guess it?
0
 
LVL 2

Expert Comment

by:k_suchdeva
Comment Utility
Yes that's what it should do.
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 15

Expert Comment

by:mohan_sekar
Comment Utility
Hi desisant,

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

0
 
LVL 15

Accepted Solution

by:
ozymandias earned 300 total points
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
Thanks A lot!
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
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 learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

744 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now