• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 203
  • Last Modified:

Simple application

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
desisant
Asked:
desisant
  • 4
  • 2
  • 2
  • +5
1 Solution
 
rrzCommented:
There is a program very similar to what you describe.
It is distributed as an example JSP page with Tomcat 3.2
0
 
shahnazaliCommented:
This is a doubt or ur home assignment ?
0
 
desisantAuthor Commented:
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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
k_suchdevaCommented:
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
 
ccaprarCommented:
Didn't you mean the computer picks a number and the user tries to guess it?
0
 
k_suchdevaCommented:
Yes that's what it should do.
0
 
mohan_sekarCommented:
Hi desisant,

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

0
 
ozymandiasCommented:
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
 
ozymandiasCommented:
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
 
mzimmer74Commented:
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
 
ozymandiasCommented:
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
 
ozymandiasCommented:
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
 
desisantAuthor Commented:
Thanks A lot!
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 4
  • 2
  • 2
  • +5
Tackle projects and never again get stuck behind a technical roadblock.
Join Now