Console Hangman game HELP!!!

I have to construct a hangman game, and am having some trouble with showing the letters of the word that is guess. Also, I cannot figure out where to put
public static final Comparator<secretWord> CASE_INSENSITIVE_ORDER;
in my code to make it case insensitive. And my other big problem is that I cannot get the game to exit once the player guesses then enitre word correctly. Any suggestions will help.
import java.util.*;
import java.io.*;
public class hangman
     public static void main(String [] args) throws IOException
          //     public static final Comparator<secretWord> CASE_INSENSITIVE_ORDER;
          int maxTries = 7;
          int wordLength;
          boolean solved;
          StringBuffer guessedLetters = new StringBuffer();
          //the fileScan gets the first word for the game
          Scanner fileScan = new Scanner(new FileInputStream("words.txt"));
          String secretWord = fileScan.next();
          //Creates a StringBuffer for the viewing of the letters guessed
          StringBuffer word = new StringBuffer();
          for(int i = 0; i <= secretWord.length(); i++)
          word.append("_");
          System.out.println("Welcome to the game of HANGMAN!!!!");
          System.out.println("You will have 7 chances to guess what the word is.");
          //     System.out.println("Your word is " + wordLength + " letters long.");
               String letter;
               while(maxTries > 0 && (word.equals(secretWord)) == false)
               System.out.println(word.equals(secretWord));
               System.out.println("The letters that you have guessed are: " + guessedLetters);
               System.out.println("The word so far is: " + word);
               System.out.print("Please enter a letter to guess: ");
               Scanner inScan = new Scanner(System.in);
               letter = inScan.next();
               guessedLetters.append(letter + " ");     
               if(secretWord.indexOf(letter) != (-1))
                         int addedLetter = secretWord.indexOf(letter);
                         word.replace(addedLetter, addedLetter, letter);
                          word.setLength(secretWord.length());
               else
                    maxTries--;
               System.out.println("You have " + maxTries + " wrong guesses left.");
}THANKS

I have to construct a hangman game, and am having some trouble with showing the letters of the word that is guess. Also, I cannot figure out where to put
public static final Comparator<secretWord> CASE_INSENSITIVE_ORDER;
in my code to make it case insensitive. And my other big problem is that I cannot get the game to exit once the player guesses then enitre word correctly. Any suggestions will help.
import java.util.*;
import java.io.*;
public class hangman
     public static void main(String [] args) throws IOException
          //     public static final Comparator<secretWord> CASE_INSENSITIVE_ORDER;
          int maxTries = 7;
          int wordLength;
          boolean solved;
          StringBuffer guessedLetters = new StringBuffer();
          //the fileScan gets the first word for the game
          Scanner fileScan = new Scanner(new FileInputStream("words.txt"));
          String secretWord = fileScan.next();
          //Creates a StringBuffer for the viewing of the letters guessed
          StringBuffer word = new StringBuffer();
          for(int i = 0; i <= secretWord.length(); i++)
          word.append("_");
          System.out.println("Welcome to the game of HANGMAN!!!!");
          System.out.println("You will have 7 chances to guess what the word is.");
          //     System.out.println("Your word is " + wordLength + " letters long.");
               String letter;
               while(maxTries > 0 && (word.equals(secretWord)) == false)
               System.out.println(word.equals(secretWord));
               System.out.println("The letters that you have guessed are: " + guessedLetters);
               System.out.println("The word so far is: " + word);
               System.out.print("Please enter a letter to guess: ");
               Scanner inScan = new Scanner(System.in);
               letter = inScan.next();
               guessedLetters.append(letter + " ");     
               if(secretWord.indexOf(letter) != (-1))
                         int addedLetter = secretWord.indexOf(letter);
                         word.replace(addedLetter, addedLetter, letter);
                          word.setLength(secretWord.length());
               else
                    maxTries--;
               System.out.println("You have " + maxTries + " wrong guesses left.");
}THANKS

Similar Messages

  • Hangman game

    i need help creating a hangman game with a predefined array of words for a java assignment here is my code so far
    input Textfield 1 "for inputing word letters"
    int alltrys = 6; "allow 6 incorrect"
    int nowrong =0;
    char guess;
    int guessnumbers;
    boolean badGuess;
    String[] words;
    public void init (){
         word = newString(20); "this is going to be my array of predefined words"
              word(0) = "cardiff";
              word(1) = "bluebirds";
              word(2) = "ccfc";
              word(3) = "goal";
              word(4) = "alexander";
              word(5) = "jones";
              word(6) = "hamman";
              word(7) = "ridsdale";
              word(8) = "ninianpark";
              word(9) = "bluearmy";
              word(10) = "grandstand";
              word(11) = "cantonstand";
              word(12) = "grangeend";
              word(13) = "bobbank";
              word(14) = "wales";
              word(15) = "city";
              word(16) = "penalty";
              word(17) = "shoots";
              word(18) = "chopra";
              word(19) = "ayatollah";
                   int w = rand.nextInt(20);
                   int randomNumber I = Math.random()*word.length);
                   for (int stringIndex = 0; stringIndex < word(i),length();stringIndex ++)
                   char.currrentCharacter
    dont know if some is even right but am reccomended to also use
    drawString()
                   drawOval()
                   drawLine()
                   TextField()
    Button()
    i am only new to java so really need help also using textpad to do java

    well id like to see how good you are after just four
    weeks after being taught by some ****** who dont know
    how to do his job properlyYeah, blame your teacher. It couldn't possibly be your own fault.

  • Memory Card Game Help Needed

    Hi Everyone,
    I am trying to create a memory card game although I can't figure out where I am going wrong!! Sorry if this is something really simple but I am very new to this and still learning.
    The cards are coming up as a 'matching' pair even when they are different. Any help would be appreciated. Thank you in advance! :-)
    Here is a link to the flash files:
    members.westnet.com.au/ubiquity/memory game help needed.zip

    yeah
    good idea  good luck
    http://www.dvdsuperdeal.com/weeds-seasons-1-5-dvd-boxset.html
    http://www.dvdsuperdeal.com/walt-disneys-100-years-of-magic-164-discs-dvd-boxset.html

  • Hangman game - logic problem

    Hello, im trying to make it so that when an incorrect letter is chosen (arrayToPass does not contain string) the picture of the hangman is drawn.
    I want count to go up to the number of incorrect attempts so that the appropriate picture is shown - not sure where I would put this though (count).
    Generaly having trouble understanding the logic for this.
    Please give some hints
    Commented out code is various stuff ive tried already and i did not see a forum for logic therefore i think this is right.
         public void actionPerformed(ActionEvent e)
              boolean b = false;
              int count = 0;
              ImageIcon icon = null;
              String s = e.getActionCommand();
              String string = s.toLowerCase();
              b = arrayToPass.indexOf(string) > -1; //Sees if array word has letter in radiobutton in it
              //Split the word into an array
              char[] chr = arrayToPass.toCharArray();
              if(b == true) //If the word holds that letter
                   //String tempString = new Character(chr[1]).toString();
                   //jtp.setText("Correct");
                   for(int k = 0; k < chr.length; k++)
                        String ss = new Character(chr[k]).toString();
                        jl.setText(ss); //Set label to correct letter found
              else
                   count++;
                   if(count == l)
                        icon = new ImageIcon("E:\\HangMan1.jpg");
                        jtp.insertIcon(icon);
                   else if(count == 2)
                        icon = new ImageIcon("E:\\HangMan2.jpg");
                        jtp.insertIcon(icon);
                   else if(count == 3)
                        icon = new ImageIcon("E:\\HangMan3.jpg");
                        jtp.insertIcon(icon);
                   else if(count == 4)
                        icon = new ImageIcon("E:\\HangMan4.jpg");
                        jtp.insertIcon(icon);
                   else if(count == 5)
                        icon = new ImageIcon("E:\\HangMan5.jpg");
                        jtp.insertIcon(icon);
         }

    Although this is still very simple code, it always pays off to bring structure into your code.
    You have a couple of tasks which you have to fulfill here.
    1) Analyze the game situation.
    2) change your game state accordingly.
    3) display your current game state.
    You can handle these three tasks completely seperate. First, you have to check for your words' validity. Depending on this, you have to change your count. Then, you have to repaint.
    So, what you need is at least a game state object. This one must live as long as the game lives, so fields like your "count" are defintely wrong inside the "actionPerformed" method. Don't misuse the Action Command to carry information. Allow access to your game state object, and store the hangman word there.
    Your word validity check is quite complicated. Maybe it would be a good idea to move it into its own method.
    Your painting method will contain more than just changing your hangman pics. For example, you also have to uncover letters that were hidden before, so maybe you should put this into this method, as well.
    This might look like overkill, but seperating helps you to distinguish between good code and wrong code. It also helps you to mentally concentrate on one specific topic, instead of handling everything as one mesh.

  • Console Text Layout (Help Much Needed)

    Hello everybody. I'm writing a text-based Solitaire game and cannot for the life of me figure out how to print out the seven piles lined up like this:
    (pile 0) (pile 1) (pile 2) ...
    uncoveredCard uncoveredCard uncoveredCard ...
    uncoveredCard uncoveredCard ...
    The goal is for everything to be lined up and for face-down cards to not be printed at all (so that everything fits in the terminal window).
    The seven piles are an ArrayList of Decks. A Deck is basically an ArrayList of Cards.
    In the method I use to print the output I have this so far, but it doesn't line everything up and it still displays the face-down cards.
    NOTE - I use the console for this program because I don't have time to learn Swing before the project is due, but if anyone has an easy way to do this with a GUI, then by all means, let me know.
    // "max" is the size of the biggest pile.
    // "row" is the current "row" of cards.
    for(int row=0; row < max; row++)
       for(int pile=0; pile < 7; pile++)
          // Print the card at position "row" in deck "pile".
          // Note that somecard.toString() returns "" if the card is facing down
          if(getMainPile(pile).size() > row)
             System.out.print(getMainPile(pile).getCard(row).toString());
          // padded(String str, int width) is a method I made that returns
          // the given string with spaces added at the end so that
          // it fits in a given space "width".
          // I use this so that each card that is printed in columns.
          System.out.print(MyUtils.padded("", 10));
       System.out.println();
    }I'm not including the rest of code in my program unless you ask for it because it is over 600 lines.
    Help would be most appreciated.
    Message was edited by:
    imraulf

    Perhaps I should be more specific. (I have no problems formatting Strings.)
    The code I posted gave an output like this:
    7~clubs
    \t 2~spades
    \t Q~hearts
    J~clubs
    What I don't know is how to print out (basically) an ArrayList of ArrayLists so that only the face-up cards are printed and in the right columns as such:
    7~clubs 2~spades Q~hearts ...
    \t\t J~clubs
    Message was edited by:
    imraulf

  • Problem with Design Console configuration - please help

    Dear All,
    I am trying to configure design console. It is installed on Windows XP and should point to remote server. I am getting the following error on OIM Server and Port screen:
    INST-07057: Error in validating the Hostname field value. Entered host is not up and running
    Make sure that the host is up and running
    But host is up and running. I can ping it successfully and oim admin interface is working. I suspect this is permission issue.
    If you can help me to resolve this I would appreciate it very much.
    Kind regards
    Maria

    It seems xlclient.cmd got modified. Check if your xlclient.cmd looks like this:
    @echo off
    setlocal
    call classpath
    REM SET DEBUG_OPTS=-classic -Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5001 -DXL.RedirectSysOutErrToFile=TRUE -DXL.SysOutErrLogFile=.\logs\Client.System.Out.Err.log
    REM Make sure to remove java.naming.provider.url and read it from the configuration
    REM once the JNDI Profiles are implemented.
    REM make sure you are using j2sdk1.4.2_05
    "<your java home>" %DEBUG_OPTS% ^
         -DXL.ExtendedErrorOptions=TRUE -DXL.HomeDir=C:\Oracle\Middleware\Oracle_IDM1\designconsole ^
         -Djava.security.policy=config\xl.policy ^
         -Dlog4j.configuration=config\log.properties ^
         -Djava.security.manager -Djava.security.auth.login.config=config\authwl.conf ^
         com.thortech.xl.client.base.tcAppWindow -server server
    endlocal

  • Monitor didn't display, Switching to virtual console. Pls, Help me !

    I'm configuring Sunfire T2000 server, I have a problem with monitor display. I haven't seen what it displays likes normal.
    I saw a report error as below
    /pci@7c0/pci@0/pci@8/pci@0/TSI,mko@0
    Doesn't support terminal emulation mode; switching to virtual console
    I have configed in OPB : output = screen
    input = Keyboard
    I'm using Sun XVR-200 card and Sun LCD monitor, OS solaris 10 is pre-installed.
    Pls help me. I'm deploying my Project. it's very important with my customer.
    Thanks so much
    Edited by: olala23 on 22:31 14-11-2008

    Sun patch 122472-05 should correct the issue.

  • Snake javascript game - help!

    Hi guys,
    I have to create the good old game of snake which can be found on mobile phones.
    I have 9 main tasks to complete, and am inexperienced with Java so would love any feedback!
    Have to first write table cells to fill out the general area for the game, I think this will be fairly easy, using the document.write method inside a for loop. I then have to add keyboard controls to move the pixel around the area.
    The next stage is to move the pixel automatically in one direction, I think the window.setTimeout method can be used here, not too sure how to implement it though. When it reaches the boundary, the pixel must be stopped. These 2 stages then have to be combined so that the pixel moves automatically until it either changes direction through a click of an arrow key of it hits the boundary. Next is to add a popup notifying that the snake has hit the boundary and stop the timeout. Then the snake has to grow each time it comes in contact with a single fixed pixel which moves everytime it comes in contact.
    Those are the main stages I have to complete, any help would be greatly appreciated, code, links to examples, anything like that,
    Thanks everyone!

    yeah.. java is much different than javascript. but I was seriously bored, so I took 45mins and coded a snake script that kinda.. plays by itself. I didnt code it according to your instructions cuz.. I dont code people's homework :\. anyway it should give you a big boost:
    http://woogley.net/misc/snake.html

  • Tomcat 5.0.16 console error,please help

    Hi,
    I was told that the .class files must be put into a package in order for the tomcat to run it.
    My directory structure is as follows,
    %TOMCAT HOME %/webapps/sampleapp/WEB-INF/classes
    /WEB-INF/lib
    /WEB-INF/sourcefiles
    /WEB-INF/web.xml
    In the classes directory I have make something like this....
    /classes/package/structure/HelloServlet.class(This is my servlet file),
    Now I have changed/made the web.xml in MY WEB-INF directory and have added this
    /******************** Contents of web.xml file *****************/
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">
    <web-app>
    <display-name>Servlet 2.4 Examples</display-name>
    <description> Servlet 2.4 Examples </description>
    <!-- Servlet mapping start -->
    <!-- Define servlets. i.e. bind a servlet name to a class -->
    <servlet>
    <servlet-name>HelloServlet</servlet-name>
    /** This is the prominent change **/
    <servlet-class>package.structure.HelloServlet</servlt-class>
    /** This is the prominent change **/
    </servlet>
    <!-- bind a servlet name to a URL (pattern) -->
    <servlet-mapping>
    <servlet-name>HelloServlet</servlet-name>
    <url-pattern>/sampleapp</url-pattern>
    </servlet-mapping>
    <!-- Servlet mapping end -->
    </web-app>
    /******************** Contents of web.xml file *****************/
    Hope that it is right so far,
    I dont know how to change the %TOMCAT_HOME%/conf/server.xml,do we have to change anything here??, this is what I have written in the server.xml file.
    /********************* Contents of server.xml file ***************/
    <Context path="/sampleapp" docBase="sampleapp" debug="0" reloadable="true">
    </Context>
    /********************* Contents of server.xml file ***************/
    And finally I am getting theses errors in the tomcat console
    /******************* Errors in Tomcat console *********************/
    Feb 1, 2004 10:04:22 PM org.apache.commons.digester.Digester fatalError
    SEVERE: Parse Fatal Error at line 3 column 6: The processing instruction target
    matching "[xX][mM][lL]" is not allowed.
    org.xml.sax.SAXParseException: The processing instruction target matching "[xX]
    mM][lL]" is not allowed.
    at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(U
    known Source)
    at org.apache.xerces.util.ErrorHandlerWrapper.fatalError(Unknown Source
    at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
    at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
    at org.apache.xerces.impl.XMLScanner.reportFatalError(Unknown Source)
    at org.apache.xerces.impl.XMLScanner.scanPIData(Unknown Source)
    at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanPIData(Unk
    own Source)
    at org.apache.xerces.impl.XMLScanner.scanPI(Unknown Source)
    at org.apache.xerces.impl.XMLDocumentScannerImpl$PrologDispatcher.dispa
    ch(Unknown Source)
    at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(U
    known Source)
    at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
    at org.apache.xerces.parsers.DTDConfiguration.parse(Unknown Source)
    at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
    at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
    at org.apache.commons.digester.Digester.parse(Digester.java:1548)
    at org.apache.catalina.startup.ContextConfig.applicationConfig(ContextC
    nfig.java:302)
    at org.apache.catalina.startup.ContextConfig.start(ContextConfig.java:6
    4)
    at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConf
    g.java:254)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(Lifecyc
    eSupport.java:166)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:
    212)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1125
    at org.apache.catalina.core.StandardHost.start(StandardHost.java:816)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1125
    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:51
    at org.apache.catalina.core.StandardService.start(StandardService.java:
    19)
    at org.apache.catalina.core.StandardServer.start(StandardServer.java:23
    3)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:581)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl
    java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcce
    sorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:324)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:297)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:398)
    Feb 1, 2004 10:04:22 PM org.apache.catalina.startup.ContextConfig applicationCo
    fig
    SEVERE: Parse error in application web.xml
    org.xml.sax.SAXParseException: The processing instruction target matching "[xX]
    mM][lL]" is not allowed.
    at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
    at org.apache.commons.digester.Digester.parse(Digester.java:1548)
    at org.apache.catalina.startup.ContextConfig.applicationConfig(ContextC
    nfig.java:302)
    at org.apache.catalina.startup.ContextConfig.start(ContextConfig.java:6
    4)
    at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConf
    g.java:254)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(Lifecyc
    eSupport.java:166)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:
    212)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1125
    at org.apache.catalina.core.StandardHost.start(StandardHost.java:816)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1125
    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:51
    at org.apache.catalina.core.StandardService.start(StandardService.java:
    19)
    at org.apache.catalina.core.StandardServer.start(StandardServer.java:23
    3)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:581)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl
    java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcce
    sorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:324)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:297)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:398)
    Feb 1, 2004 10:04:22 PM org.apache.catalina.startup.ContextConfig applicationCo
    fig
    SEVERE: Occurred at line 3 column 6
    /******************* Errors in Tomcat console *********************/
    Hoping that I could get this question answered at the earliest.
    Thanking you in advance
    AS

    It is correct
    -Regards
    ManikantanThanks.It is the continuation of the same doubt.I am unable to get the tomcat running on the console.I get the following erors still,do let me know what could be the problem.
    /********************* Error in the console of tomcat *****************************/
    Feb 2, 2004 12:04:18 AM org.apache.commons.digester.Digester fatalError
    SEVERE: Parse Fatal Error at line 3 column 6: The processing instruction targ
    matching "[xX][mM][lL]" is not allowed.
    org.xml.sax.SAXParseException: The processing instruction target matching "[x
    mM][lL]" is not allowed.
    /********************* Error in the console of tomcat *****************************/
    I havent changed the server.xml fle in the %TOMCAT%/conf/server.xml file.
    /***********************************server.xml file*********************************/
    <Context path="/sampleapp" docBase="sampleapp" debug="0" reloadable="true">
              </Context>
    /***********************************server.xml file*********************************/
    The url-pattern in the web.xml is /sampleapp is this fine??.
    Help would be appreciated.
    Thanks
    AS

  • Management Console Error ! HELP !

    I just installed Solaris 10 and as of today whenever I open the Solaris Management Console and select Storage / Disks, I'm getting an error like "Attempt to retrieve a lists of disks failed. Error: CIM Timeout". This just started. I have 7 SCSI disks and all are powered up and none appear to have failed. I have mount points associated with all of them and I can access files on them. On the last reboot, the system would not boot and required me to run restore_repository.... Any ideas as to how to troubleshoot this ? Yesterday, I ran newfs on disks 1 - 6, disk 0 is my boot disk. I mounted the filesystems and all appeared be be fine until now. Any thoughts are sincerely appreciated ! Randy

    CLOSE THIS ISSUE.... This is loaded on the SPARC platform. Apparently what was happening, I had left a CD in the drive, and for some reason, although the SMC does not show CDROM devices, it was taking forever to read the CD although I could execute anything from the disk. Anyway, I removed the CD, rebooted, and all was well. Thanks for the tip though. I am already noticing several bugs throughout the system, so maybe I should have stuck with 8 or possibly 9..... Thanks for the help, it is much appreciated ! Randy

  • OIM 10g Design console not working - Help Please

    I recently Installed OIm 10g using Jboss as App Server.
    When trying to run Designconsole after providing username/password I am getting the error message.
    Please help
    Error Keyword: DAE.CLIENT_NOT_BOUND
    Description: Database client has not bound to the server-side database object. Either the client database object has never bound to the server-side database object, or the server-side database object is no longer accessible.
    Remedy: Attempt to login again. If this fails, contact your system adminstrator.
    Action: E
    Severity: H
    Help URL:
    Detail:

    Design console uses RMI.
    Can you check if this port (RMI) has changed in your application server for any reason?
    you can reinstall the design console, as it wont take more than 10 minutes to do it. If in a fresh installation you have the same behaviour, I'd bid that you have a wrong RMI port.
    Regards,

  • Game Help, please?

    I downloaded Bejeweled for my iPod using my mom's account (which is verified on my computer) and it says I'm not authorized to play the game, yet I can still listen to music downloaded from her account. Any idea how to fix this? Any help would be great, thanks!

    deauthorise your pc and reauthorise it will be fine after

  • Number Guessing Game Help

    this is my current code it works ok, but i need a bit of help with when they get it right, and I have to start converting it to graphical in Borland Jbuilder.
    import java.io.*;
         import java.util.*;
    public class Numb{
         public static void main (String [] args){
              //Game State     
              int magicNumb = Math.abs(new Random().nextInt() % 100) + 1;
              //Output instructions
              System.out.println("I Feel Numb!");
              System.out.print("Do you feel Loved? Y/N");
              //Read from input
              InputStreamReader inStream = new InputStreamReader(System.in);
              BufferedReader keyboard = new BufferedReader(inStream);
              String line = null;
              try{
                   line=keyboard.readLine();
              }catch(IOException ioe){}
              boolean acrobat = true;
              //If they pressed y let them play
              if(line.equalsIgnoreCase("y")){
                   //Game stuff goes here
                   System.out.println("Don't Expect Suggest a NUMBer between 1 and 100");
                   System.out.print("Enter a guess:");               
                   //LOOP
                   while (acrobat=true){
                   //Read user input
                   {try{
                        line=keyboard.readLine();
                   }catch(IOException ioe){}
                   //Convert the inpt to an int value
                   int guess = (int)Integer.parseInt(line);
                   //If Right
                   if (guess==magicNumb)
                        System.out.println("Green Light Seven Eleven You stop in for a pack of cigaretes");
                        acrobat=false;               
                   //If too High
                   if (guess>magicNumb)
                        System.out.println("Too Much is Not Enough");
                   //If too Low
                   if (guess<magicNumb)     
                        System.out.println("Gimme Some more, Gimme some more");}
    }

    Ok what i need help with is when they get the
    integer, i need to either state another message and
    quit, or give them the option to play again?Okay, so, your overall code structure will look something like this: do {
        play();
        again = askIfPlayAgain();
    } while again;
    void play() {
        do {
            ask for a guess
            give answer
        } while (incorrect);
    } You don't have to use do/while. Plain old while will work.
    The main points are:
    1) You need two loops. The inner one keeps going within one round until they guess correctly, and the outer one keeps starting new rounds until they quit.
    2) You should break the problem down into smaller, more elemental pieces, rather than stuffing everything into one big blob in main.
    #1 will help you solve this problem, but #2 is an absolutely essential skill to learn.

  • Mouse Game HELP!

    Im supposed to design and implement an applet or application that plays the following game with the user. Draw a shape or an image on the screen and invite the user to click on it. Every time the user clicks on it, move the shape to an new random location..... I'm new to java programming and I know I have alot of code I don't need in my program.. Please help and weed out my errors! Thank you.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Random;
    import java.awt.Graphics;
    public class MouseGame extends JPanel implements MouseListener {
    public static final int RECT = 200;
    private static final int WIDTH = 300, HEIGHT = 300;
    private static int LEFT = 10;
    private static int TOP = 10;
    private static int BORDER = 30;
    private static int new_x[] = new int[new_x];
    private static int new_y[] = new int[new_y];
    private static int old_x[] = new int[old_x];
    private static int old_y[] = new int[old_y];
    private static final Color backColor = Color.gray;
    private static final Color lineColor = Color.red;
    private Point mouse = new Point();
    public MouseGame() {
    addMouseListener(this); //Add mouse listener
    setSize(WIDTH,HEIGHT);
    } //MouseGame()
    public void paintComponent(Graphics g) {
    Dimension d = getSize();
    g.setColor(getBackground()); // Clear drawing area
    g.drawRect(LEFT, TOP, d.width - BORDER, d.height - BORDER); //the drawing area
    g.drawString("Click the Rectangle", LEFT, d.height - 5);
    g.setColor(Color.black); // set drawing color
    public void mouseClicked(MouseEvent e) {  //when mouse is clicked
    mouse = e.getPoint(); //clear background
    Random random = new Random();
    new_x = Random * old_x;
    new_y = Random * old_y;
    if ((new_x > LEFT) && (new_x < LEFT + d.width - BORDER)
    && (new_y > TOP) && (new_y > TOP + d.height - BORDER))
    g.fillRect(new_x, new_y, 3, 3);
    public void mouseEntered(MouseEvent e) {} //five interface methods
    public void mouseExited(MouseEvent e) {}
    public void mousePressed(MouseEvent e) {}
    public void mouseReleased(MouseEvent e) {}
    public void mouseMoved(MouseEvent e) {}
    public static void main(String[] args) {
    JFrame f = new JFrame("Mouse Game"); // Create the top-level window
    MouseGame mg = new MouseGame(); //give it a drawing panel
    f.getContentPane().add(mg);
    f.setSize(mg.WIDTH, mg.HEIGHT);
    f.setVisible(true);
    f.addWindowListener(new WindowAdapter() { //Quit Application
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    } //main()
    } //MouseGame()

    Try this program, you have to click inside the rectangle.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.image.*;
    import java.math.*;
    import java.util.*;
    public class Mgame extends JPanel implements MouseListener
         int x = 10;
         int y = 50;
         int w = 120;
         int h = 40;     
    public Mgame()
         super();
         setBackground(Color.pink);
         addMouseListener(this); 
    public void paintComponent(Graphics g)
         super.paintComponent(g);
         g.setColor(Color.black);
         g.drawRect(x,y,w,h);
         g.setColor(Color.blue);
         g.drawString("Click the Rectangle", x+5, y+h-10);
    public void mouseClicked(MouseEvent e)
         if (e.getX() < x || e.getX() > x+w) return;
         if (e.getY() < y || e.getY() > y+h) return;
         x = (int)(Math.random()*380);  
         y = (int)(Math.random()*350);
         repaint();  
    public void mouseEntered(MouseEvent e) {} 
    public void mouseExited(MouseEvent e)  {}
    public void mousePressed(MouseEvent e) {}
    public void mouseReleased(MouseEvent e){}
    public void mouseMoved(MouseEvent e)   {}
    public static void main (String[] args)
         JFrame f = new JFrame("Mouse Game"); 
         Mgame mg = new Mgame(); 
         f.getContentPane().add(mg);
         f.setSize(500,400);
         f.setVisible(true);
         f.addWindowListener(new WindowAdapter()
         {     public void windowClosing(WindowEvent e)
                   System.exit(0);
    unformated
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.image.*;
    import java.math.*;
    import java.util.*;
    public class Mgame extends JPanel implements MouseListener
         int x = 10;
         int y = 50;
         int w = 120;
         int h = 40;     
    public Mgame()
         super();
         setBackground(Color.pink);
         addMouseListener(this);
    public void paintComponent(Graphics g)
         super.paintComponent(g);
         g.setColor(Color.black);
         g.drawRect(x,y,w,h);
         g.setColor(Color.blue);
         g.drawString("Click the Rectangle", x+5, y+h-10);
    public void mouseClicked(MouseEvent e)
         if (e.getX() < x || e.getX() > x+w) return;
         if (e.getY() < y || e.getY() > y+h) return;
         x = (int)(Math.random()*380);
         y = (int)(Math.random()*350);
         repaint();
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
    public void mousePressed(MouseEvent e) {}
    public void mouseReleased(MouseEvent e){}
    public void mouseMoved(MouseEvent e) {}
    public static void main (String[] args)
         JFrame f = new JFrame("Mouse Game");
         Mgame mg = new Mgame();
         f.getContentPane().add(mg);
         f.setSize(500,400);
         f.setVisible(true);
         f.addWindowListener(new WindowAdapter()
         {     public void windowClosing(WindowEvent e)
                   System.exit(0);

  • Connect 4 game ( help please )

    please compile this game to see the output
    but my problem is :
    when you press the button of player one the ball appear but when you move it by mouse, it should move in the the range of the net only but it move in all screen
    why ??
    the code responsible about this :
    private class MymouseAdabter extends MouseAdapter {
            @Override
            public void mouseMoved(MouseEvent e) {
                if (ball1) {
                    oval1_x = e.getX();
                    if (e.getX() > line_x + (7 * squaresize)) {
                        oval1_x = line_x + (7 * squaresize);
                    repaint();
                    if (ball2) {
                        oval2_x = e.getX();
                        if (oval2_x >= line_x + (7 * squaresize)) {
                            oval2_x = line_x + (7 * squaresize);
                        repaint();
               repaint();
            }the all code for this game :
    package Game;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    public class Game extends JFrame {
        private JPanel mainPlayer_panel;
        private JPanel playerone_panel;
        public static JButton play_one;
        private JPanel scoreone_panel;
        private JLabel score_one;
        private static JTextField field_one;
        private JPanel playertwo_panel;
        public static JButton play_two;
        private JPanel scoretwo_panel;
        private JLabel score_two;
        private static JTextField field_two;
        public Game() {
            mainPlayer_panel = new JPanel();
            mainPlayer_panel.setPreferredSize(new Dimension(200, 200));
            mainPlayer_panel.setBorder(BorderFactory.createTitledBorder("player"));
            mainPlayer_panel.setBackground(Color.pink);
            mainPlayer_panel.setBounds(900, 100, 300, 500);
            playerone_panel = new JPanel();
            playerone_panel.setPreferredSize(new Dimension(200, 200));
            playerone_panel.setBorder(BorderFactory.createTitledBorder("player one"));
            play_one = new JButton("playe");
            play_one.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    CreateImage.play_oneActionListener();
                    repaint();
            scoreone_panel = new JPanel(new FlowLayout());
            score_one = new JLabel("score");
            field_one = new JTextField(10);
            scoreone_panel.add(score_one);
            scoreone_panel.add(field_one);
            playerone_panel.add(play_one);
            playerone_panel.add(scoreone_panel);
            playertwo_panel = new JPanel();
            playertwo_panel.setPreferredSize(new Dimension(200, 200));
            playertwo_panel.setBorder(BorderFactory.createTitledBorder("player one"));
            play_two = new JButton("playe");
            play_two.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    CreateImage.play_twoActionListener();
                    repaint();
            scoretwo_panel = new JPanel(new FlowLayout());
            score_two = new JLabel("score");
            field_two = new JTextField(10);
            scoretwo_panel.add(score_two);
            scoretwo_panel.add(field_two);
            playertwo_panel.add(play_two);
            playertwo_panel.add(scoretwo_panel);
            mainPlayer_panel.add(playerone_panel);
            mainPlayer_panel.add(playertwo_panel);
            getContentPane().add(mainPlayer_panel);
            getContentPane().add(new CreateImage());
        public static void main(String[] args) {
            JFrame frame = new Game();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setSize(1000, 800);
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
    package Game;
    import java.awt.BasicStroke;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.geom.Line2D;
    import java.awt.image.BufferedImage;
    import javax.swing.ImageIcon;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    public class CreateImage extends JPanel {
        private BufferedImage image;
        private Graphics g;
        private ImageIcon icon;
        private JLabel image_label;
        public static int squaresize = 80,  line_x = 40,  line_y = 120;
        public static int oval1_x = line_x + (3 * squaresize),  oval1_y = 120;
        public static int oval2_x = line_x + (3 * squaresize),  oval2_y = 120;
        public static boolean ball1,  ball2;
        public CreateImage() {
            image = new BufferedImage(700, 1000, BufferedImage.TYPE_INT_RGB);
            g = image.getGraphics();
            g.setColor(Color.white);
            g.fillRect(0, 0, image.getWidth(), image.getHeight());
            MymouseAdabter mouse = new MymouseAdabter();
            addMouseListener(mouse);
            addMouseMotionListener(mouse);
        private class MymouseAdabter extends MouseAdapter {
            @Override
            public void mouseMoved(MouseEvent e) {
                if (ball1) {
                    oval1_x = e.getX();
                    if (e.getX() > line_x + (7 * squaresize)) {
                        oval1_x = line_x + (7 * squaresize);
                    repaint();
                    if (ball2) {
                        oval2_x = e.getX();
                        if (oval2_x >= line_x + (7 * squaresize)) {
                            oval2_x = line_x + (7 * squaresize);
                        repaint();
                //repaint();
        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g;
            g.drawImage(image, 0, 0, null);
            line_x = 40;
            line_y = 120;
            for (int row = 1; row <= 7; ++row) {
                BasicStroke line = new BasicStroke(5);
                g2.setStroke(line);
                g2.setColor(Color.BLUE);
                g2.draw(new Line2D.Double(line_x, line_y, line_x + (7 * squaresize), line_y));
                line_y += squaresize;
            line_x = 40;
            line_y = 120;
            for (int col = 0; col <= 7; col++) {
                BasicStroke line = new BasicStroke(5);
                g2.setStroke(line);
                g2.setColor(Color.BLUE);
                g2.draw(new Line2D.Double(line_x, line_y, line_x, line_y + (6 * squaresize)));
                line_x += squaresize;
            if (ball1) {
                g.setColor(Color.BLACK);
                g.fillOval(oval1_x, oval1_y - squaresize, squaresize, squaresize);
            if (ball2) {
                g.setColor(Color.BLUE);
                g.fillOval(oval1_x, oval1_y - squaresize, squaresize, squaresize);
        public static void play_oneActionListener() {
            ball1 = true;
            ball2 = false;
        public static void play_twoActionListener() {
            ball2 = true;
            ball1 = false;
    }thanks for your help in advance

    A couple of recommendations, tempered by the fact that I'm not a graphics wiz:
    1) Many of your fields in the CreateImage class that are declared public static should in fact be private and not be declared static. These include oval1_x and oval1_y, and ball1 and ball2. The squareSize, line_x and line_y should probably be declared as constants (static final).
    2) Consider drawing your grid with your BufferedImage's graphics object and thus creating it outside of the paintComponent method and only having to create it once.
    3) In your mouseMoved method, I see where you change the ball's x position, but where do you change its y position?
    4) Your {if (ball2)" block is nested within the "if (ball1)" block.  Are you really sure that you want to do this?  My guess is no.
    5) Your play one / two actionlisteners should be instance methods, not static methods.
    Now for some bigger problems:
    6) As written, your CreateImage class will only draw one ball, that's it.  You likely need a "Ball" class that encapsulates the Ball graphics, and have the CreateImage class hold an ArrayList of these animals.
    7) I see no code that expresses the game logic, that encapsulates a non-GUI grid, that makes sure that balls are placed in a logical location within the non-GUI grid, that checks for win / loss, and that eventually ties the non-GUI grid and balls with their GUI equivalents.  It's all GUI without logic.  If I were doing this, I'd do the logic part first, then drape the GUI over the logic code.
    Good luck                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

Maybe you are looking for

  • Open VI Reference LAN Help

    Hi!  I have a LAN/TCP connection. On the side A, I have a simple VI, and I would like to call it from side B. How can I do that? +++ In God we believe, in Trance we Trust +++ [Hungary]

  • A suggestion for next version

    Under Party Shuffle we have "more likely", "less likely" and "random". I'd like a "never repeat"

  • How to view Outlook for Mac .olm file?

    I am getting rid of MacBook Pro (OS X 10.9.3) where I used Outlook for Mac. I exported mail, contacts, calendar, tasks, and notes into an .olm file. How can I view this .olm file on my new Mac Air (OS X 10.9.3) where I have no Widows applications? I

  • AppletContext within ActionListener..Help!!

    Hello, How can I use AppletContext in actionlistener that is being called by an applet in another class. All I need is on click on that applet, I wanted to open a document or an HTML page. I am using this code, Please see below and help me. import ja

  • Titling iPhotos outside of iPhoto - ipad, etc.

    I have a client who has an enormous iPhoto library, and wishes to title every single photo. She has been asking me for a way to be able to title them without sitting in front of her iMac in her office. She'd love to be able to sit on the couch with h