The Artima Developer Community
Sponsored Link

Java Answers Forum
Coding

3 replies on 1 page. Most recent reply: Dec 8, 2002 3:32 AM by Thomas SMETS

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 3 replies on 1 page
Ernie Douglas

Posts: 18
Nickname: y2j
Registered: Nov, 2002

Coding Posted: Dec 6, 2002 9:02 AM
Reply to this message Reply
Advertisement
Could someone show me coding for the following: -
I need to know how to show a dialog box that allows the user to enter there FIRST Name, Once they have done that and clicked Ok, the user must enter the range of numbers that are to be used to generate the random number the user has to guess. First enter the minimum number. Ensure that this entry is numeric. If not generate an appropriate error message, and ask the user to re-enter it. This will require some sort of loop that keeps asking for a valid minimum number until one is entered! Once the minimum number has been successfully entered, prompt for the maximum number in the range of numbers to be guessed atAgain, ensure that the maximum number entered is a valid integer. Also, ensure that the maximum number is greater than the minimum number, i.e., range 200 ? 10, is an invalid range!

Once both the minimum and maximum values of the range of numbers to be guessed at and have been successfully entered, calculate the expected minimum number of guesses it should take to guess a random number within the given range. To calculate 25 in Java, use: Math.pow( 2, 5 ); ALL COnfusing for me, if anyone can understand it, ur one genius, this is for GUESS THE NUMBER, i have started it off, but not able to finish it without this. here is my coding, mite help
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class guessnumber extends Applet implements Runnable, ActionListener
{
int Count = 0;
String msg;
Thread t = null;
int state;
boolean stopflag;
private Label l1, l2;
private TextField t1, t2;
private Button b1;
private int num, mynum, diff, red, blue, green, chance = 0;
private Color c;

public void init()
{
c = new Color( 0, 80, 0 );
setForeground( c );
l1 = new Label("I have kept a number between 1 and 1000.");
l2 = new Label("Can you guess this number?");
t1 = new TextField(10);
t2 = new TextField(10);
b1 = new Button("Play Again");
t2.setEditable(false);
add(l1);
add(l2);
add(t1);
add(t2);
add(b1);

t 1.addActionListener(this);
b1.addActionListener(this);
num = 1 + (int) (Math.random()*1000);
}

public void start()
{
msg = getParameter( "Guess The Number?" );
if(msg == null)
{
msg = "Guess number";
}
msg = " " + msg;
t = new Thread( this );
stopflag = false;
t.start();
}

public void run()
{
char ch;
for( ; ; )
{
try
{
repaint();
Thread.sleep(200);
ch = msg.charAt(0);
msg = msg.substring( 1, msg.length() );
msg += ch;
if(stopflag)
{
break;
}
}
catch( InterruptedException e)
{
System.out.println( "Exception" + e );
}
}
}

public void stop()
{
stopflag = true;
t = null;
}

public void paint(Graphics g)
{
setForeground(java.awt.Color.black);
g.drawString( msg, 70, 130 );
}

public void actionPerformed( ActionEvent ae )
{

if( ae.getSource() == b1 )
{
red = 255;
blue = 255;
green = 255;
c = new Color(red, green, blue);
setBackground(c);
num = 0;
num = 1 + (int) (Math.random()*1000);
chance = 0;
showStatus( "" );
t1.setEditable(true);
t2.setEditable(false);
t1.setText("");
t2.setText("");
}
else
{
mynum = Integer.parseInt(t1.getText());
chance++;
if( chance == 1 )
{
showStatus( chance + " chance over" );
}
else
{
showStatus( chance + " chances over" );
}
if( chance >= 9 )
{
t1.setText( String.valueOf(num) );
showStatus( "Your 9 chances are up" );
t1.setEditable( false );
t2.setText( "You Need Practice" );
t2.setEditable(true);
}
diff = num - mynum;
if(diff == 0)
{
setBackground(Color.pink);
t1.setEditable(false);
t2.setText("You've done it");
t2.setEditable(false);
}
else if(Math.abs(diff)>200)
{
if(diff>0)
{
t2.setText("Too Low");
}
else
{
t2.setText("Too High");
}
}
else if(Math.abs(diff)<200)
{
if(diff>0)
{
red = 255-diff;
green = 0;
blue = 0;
c = new Color(red, green, blue);
t2.setText("");
setBackground(c);
}
else if(diff<0)
{
red = 0;
green = 0;
blue = 255 + diff;
c = new Color(red, green, blue);
t2.setText("");
setBackground(c);
if (Count < 10) System.out.print ("Congrats.. you took less than 10 chances");
else
if (Count == 10) System.out.print ("Congrats .. you just made it");
else
System.out.print ("you need practice");
}}}}}


Thomas SMETS

Posts: 307
Nickname: tsmets
Registered: Apr, 2002

Re: Coding Posted: Dec 7, 2002 8:42 AM
Reply to this message Reply
Ernie,

What is the question ?
I don't mind to spend some time to help but YOU need to spend some time to simplify the matter to show us what is your real problem. The site is not a code factory but a place where you can find help.

Hoooo,
I was to forget :
Have you read this http://www.artima.com/forums/howtopost.html ?

Might consider the Preview button next time !

Thomas,

Ernie Douglas

Posts: 18
Nickname: y2j
Registered: Nov, 2002

Re: Coding Posted: Dec 7, 2002 12:14 PM
Reply to this message Reply
this is the question
allow the player to enter their first name and the number range to use (e.g., 1 - 100, 20 - 2000, etc...) Change the output to display the player's name as well as the appropriate output message. i aslo need to Calculate the number of guesses that a player should take to find the random number given the inputted range, and use this value, rather than 10, when deciding which of the three final output messages to display when the player successfully guesses the random number.

its for Guess the number Game

Thomas SMETS

Posts: 307
Nickname: tsmets
Registered: Apr, 2002

Re: Coding Posted: Dec 8, 2002 3:32 AM
Reply to this message Reply
To display the user names here is a little snipplet that should help you...
package org.tls.demo.artima;
 
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
 
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.text.BadLocationException;
 
import org.apache.log4j.Logger;
 
/**
 * 
 * 
 * 
 * 
 * @author tsmets
 * @version $Revision$
 *  */
public class DemoShowName
    extends JFrame
 
{
    private static final Logger log = Logger.getLogger (DemoShowName.class);
    public static final int TXTFIELD_COLS = 20;
    public static final int TXT_AREA_ROWS = 20;
    public static final int TXT_AREA_COLS = 5;
    public static final String ACTION_NAME = "Transfert";
    
    JTextField userName = null;
    JTextArea txtArea = null;
    Container contentPane = null;
    JButton action = null;
    /**
     * Constructor for DemoShowName.
     */
    public DemoShowName (String frameName)
    {
       super (frameName);
       contentPane = getContentPane();
       contentPane.setLayout (new BorderLayout ());
       userName = new JTextField (TXTFIELD_COLS);
       txtArea = new JTextArea (TXT_AREA_ROWS, TXT_AREA_COLS);
       action = new JButton (ACTION_NAME);
       contentPane.add (userName, BorderLayout.NORTH);
       contentPane.add (txtArea, BorderLayout.CENTER);
       contentPane.add (action, BorderLayout.SOUTH);
       action.addActionListener (new Transfert ());
       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       setVisible(true);
       pack();
       log.debug ("Application is started");
     }
    
    /**
     * Entry point of the program
     * */    
    public static void main (String[] args)
    {
        new DemoShowName ("Demo Artima");
    }  
    
    public class Transfert
        implements ActionListener
    {        
       /**
        * @see java.awt.event.ActionListener#actionPerformed(ActionEvent)
        */
        public void actionPerformed(ActionEvent ae)
        {
          try
          {
            log.info ("public void actionPerformed ( ActionEvent " + ae + " )");
            String s = txtArea.getDocument().getText(0, txtArea.getDocument().getLength());
            log.debug ("Here is the Document content : " + s);
            txtArea.setText ("Empty");
            userName.setText (s);
         } catch (BadLocationException blex)
         {
            log.warn ( "Could not fetch the text area content. Document is : " + txtArea.getDocument(),
                           blex);
         } 
       }
    }  
}
For the other proble this sniplet should be of help :
package org.tls.demo.artima;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
 
import org.apache.log4j.Logger;
 
/**
 * 
 * @author tsmets
 * @version Revision
 *  */
public class QuickAndSimpleStrategies
    implements Runnable
{
    private static final Logger log = Logger.getLogger (QuickAndSimpleStrategies.class);
    private GessesRange strategy = new CustomerGessStrategy ();
    
    QuickAndSimpleStrategies ()
    {
        log.debug ("Program started");
    }
    
	public static void main(String[] args)
	{
        new Thread (new QuickAndSimpleStrategies()).start ();
	}
    
	/**
	 * @see java.lang.Runnable#run()
	 */
	public void run ()
	{
        int min = 0;
        int max = 0;
        String line = null;      
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        do 
        {
            try
            {
                System.out.println ("Introduce two numbers (min & max) :\n\tmin : ");
                line = br.readLine();
                min = Integer.parseInt(line);
                System.out.println ("\tmax : ");
                line = br.readLine();
                max = Integer.parseInt (line);
                System.out.println ("Strategy tells me to propose : " + strategy.process(min, max) + " guesses");
                log.info ("User introduced the following two numbers. Min : " + min + " Max : " + max);
            } catch (IOException ioe)
            {
                log.warn ( "Exception thrown while processing the Inputs", 
                           ioe);
            }    
        } while (min != -1 & max != -1);    
        log.info ("Program will termiinate soon");    
	} // end of Run
    
    public interface GessesRange 
    {
        public int process (int min, int max);
    }
    
    class CustomerGessStrategy
        implements GessesRange 
    {
        public int process (int min, int max)
        {
            return 0;
        }
    }
}
Don't forget to have the log4j.jar in your classpath with a minimum log4.properties in the classpath too (At the bottom, U will find mine).

Hope it helps,

Thomas SMETS,
SCJP2 - Brussels
--




# Set root logger level to DEBUG
log4j.rootLogger=DEBUG, stdout, joone

# Joone is set to use a ConsoleAppender (in debug).
log4j.appender.stdout=org.apache.log4j.ConsoleAppender

# Joone uses PatternLayout.
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4 j.appender.stdout.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

# Joone uses a file to log
log4j.appender.joone=org.apache.log4j.RollingFileAppender
log4j.appender.jo one.File=/tmp/run.log
log4j.appender.joone.MaxFileSize=250KB
log4j.appender.joon e.MaxBackupIndex=10


# Joone uses PatternLayout.
log4j.appender.joone.layout=org.apache.log4j.PatternLayout
log4j .appender.joone.layout.ConversionPattern=%p %t %c - %m%n

Flat View: This topic has 3 replies on 1 page
Topic: Help with creating a server. Previous Topic   Next Topic Topic: INSERT

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use