Go Back   CodingForums.com > :: Server side development > Java and JSP

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 01-07-2005, 11:52 PM   PM User | #1
cwl157
New Coder

 
Join Date: Jun 2003
Posts: 92
Thanks: 0
Thanked 0 Times in 0 Posts
cwl157 is an unknown quantity at this point
looping in java help

i have a program that produces a scrambled word and the user has to unscramble it. I want to make it like a game where when you get it right the score goes up and when you get it wrong your life goes down. right now i have everything set up and it adds and subtracts correctly but im not sure about how to make it run through more then once i know i need a loop but im not sure where to put it. can someone help? Here is the code
Code:
import java.io.*;
import java.util.*;

public class Guess
{
  public static void main(String Args[])
  {
    //instructions for player
    System.out.println("Try to unscramble the words!!  All leters are in lower case.");

    int score = 0;                 //goes up if right
    int life = 5;                     //goes down if wrong
    int a = rand(1, 4);          //get random number
    String Sword = random(a);  //use random number to get random scrabbled word
    String Nword = normWord(a);  //returns normal word
    System.out.println("Word to unscramble: " + Sword);  //print scrabbled word

    //next line is the setup for reading stuff in from the user
    InputStreamReader input = new InputStreamReader(System.in);
    BufferedReader console = new BufferedReader(input);
    String line = ""; 

    try
      {
          //read the string in from the user
          System.out.print("Please enter your guess: ");
	    line = (console.readLine());
      }
      catch(IOException e) 
      { 
        System.out.println("Something went wrong with the input"); 
      }

       if(check(line,Nword))            //if you get guess right this happens
       {
       score = score + 1;
       System.out.println("Your Score = " + score);
       System.out.println("Your life = " + life);
       }

       else                                      //if you guess wrong this happens
       {
         life = life - 1;
         System.out.println("Your Score = " + score);
         System.out.print("Your life = " + life);
       }
     	
   }

  static String random (int a)              //returns scrabled word
  {

    String[] x = {"eholl", "hwat", "arlc", "hmatos"};
    String Sword = "";
    String Nword = "";

    if(a == 1)
    {
    	Sword = x[0];
        Nword = "hello";
    }

    if(a == 2)
    {
    	Sword = x[1];
        Nword = "what";
    }

    if(a == 3)
    {
    	Sword = x[2];
        Nword = "carl";
    }

    if(a == 4)
    {
    	Sword = x[3];
        Nword = "thomas";
    }

    return Sword;
  }

  static String normWord (int a)                  //returns normal word
  {

    String[] x = {"eholl", "hwat", "arlc", "hmatos"};
    String Sword = "";
    String Nword = "";

    if(a == 1)
    {
    	Sword = x[0];
        Nword = "hello";
    }

    if(a == 2)
    {
    	Sword = x[1];
        Nword = "what";
    }

    if(a == 3)
    {
    	Sword = x[2];
        Nword = "carl";
    }

    if(a == 4)
    {
    	Sword = x[3];
        Nword = "thomas";
    }

    return Nword;
  }

 static int rand(int lo, int hi)           //gets random number to get random word
 {
   Random rn = new Random();
   int n = hi - lo + 1;
   //System.out.println(n);
   int i = rn.nextInt() % n;
   //System.out.println(i);
   
    if (i < 0)
        i = -i;
   return lo + i;
 }


 static boolean check (String line, String word)  //checks to see if correct
 {
   int i = 1;
   String answer = "";

   if(line.equals(word))
   	i = 1;	
   else
     i = 0;

   if(i == 1)
   {
   System.out.println("Correct");
   return true;
   }
   else
   {
     System.out.println("Incorrect");
     return false;
   }
 }
   
}
cwl157 is offline   Reply With Quote
Old 01-08-2005, 02:02 AM   PM User | #2
turbowrx
New Coder

 
Join Date: Nov 2004
Posts: 54
Thanks: 0
Thanked 0 Times in 0 Posts
turbowrx is an unknown quantity at this point
Looks like you could use a loop just before the try statement and encapsulate everything else in main in it. Now, you'll have to set up the condition for it. You'll probably want to allow the user to disconnect at any time and stop it when the life is gone.
turbowrx is offline   Reply With Quote
Old 01-08-2005, 04:03 AM   PM User | #3
Celtboy
Regular Coder

 
Join Date: May 2002
Location: Virginia, USA
Posts: 620
Thanks: 0
Thanked 6 Times in 6 Posts
Celtboy is an unknown quantity at this point
A few suggestions:

1. Make better use of spacing to make your code readable, and use the "4 indent" rule. Readability example: line up your comment blocks.

2. Split up the main() method into smaller methods.

3. setup a boolean "isGameOver" variable, and loop that.

4. Consider setting an array of "normal" words. Then have a method jumble them. This would reduce your code, and increase maintainability.



I can write an example for you, if you would like. Please let me know.

hth,

-Celt
Celtboy is offline   Reply With Quote
Old 01-08-2005, 06:22 PM   PM User | #4
cwl157
New Coder

 
Join Date: Jun 2003
Posts: 92
Thanks: 0
Thanked 0 Times in 0 Posts
cwl157 is an unknown quantity at this point
yea if its not that big of a trouble for you and you want to you can write an example. Thanks
cwl157 is offline   Reply With Quote
Old 01-08-2005, 09:30 PM   PM User | #5
Celtboy
Regular Coder

 
Join Date: May 2002
Location: Virginia, USA
Posts: 620
Thanks: 0
Thanked 6 Times in 6 Posts
Celtboy is an unknown quantity at this point
Here's my implementation of the game:
Code:
/**************************************************************************************

>--------------------------------------------<
              File Information:
  Created  :                 January 8, 2005
  Modified :                       ---------
  Author   :                    John Collins
                           celtboy@gmail.com
  Purpose  :
  
   A game where a jumbled word is presented
   to a user, and the user attempts to guess
   the unscrambled word.
   
             -------------------

       http://www.wintrusion.com
>--------------------------------------------<
>--------------------------------------------<



>--------------------------------------<
         Class Documentation
>--------------------------------------<
class WordJumble
    
    Method name : main
    Special     : Main method
    Arguments   : Args[], <STRING>
    Return Type : <implicit true>
    
    Method name : displayInstructions
    Special     : none
    Arguments   : none
    Return Type : void
    
    Method name : getWordList
    Special     : gets a list of words
    Arguments   : none
    Return Type : <ARRAY> (string)
    
    Method name : getJumbleWord
    Special     : makes 2 calls to function str_getm()
    Arguments   : word to jumble <STRING>
    Return Type : <STRING>
    
    Method name : checkWin
    Special     : gets a list of words
    Arguments   : none
    Return Type : <BOOLEAN>
    
    Method name : checkQuit
    Special     : gets a list of words
    Arguments   : none
    Return Type : <BOOLEAN>
    
    Method name : displayFinalMessage
    Special     : gets a list of words
    Arguments   : none
    Return Type : <ARRAY> (string)
    
    Method name : playGame
    Special     : gets a list of words
    Arguments   : none
    Return Type : <ARRAY> (string)
    
    Method name : getRandomWord
    Special     : gets a random word from an array of words
    Arguments   : none
    Return Type : <STRING>

>--------------------------------------<
>--------------------------------------<



>--------------------------------------<
              Run-Through
>--------------------------------------<
1. Initialize variables
2. Display Instructions
3. Generate Word List
4. Select Random Word
5. Offer scrambled version of word to user
6. Accept User Input
7. Check input against scrambled
8. <Logic>
      -If correct: Offer quit / new word
      -If wrong: present score, get new input
9. Variable cleanup
10. Display Closing Message
      
>--------------------------------------<
>--------------------------------------<
**************************************************************************************/
import java.io.*;
import java.util.*;

public class WordJumble {

    private static int score = 0;
    private static int life  = 5;
    
    private static Random num;
    
    private static String[] wordlist;
    private static String randomWord;
    private static String jumbleWord;
    
    
    private static boolean isWinner = false;
    private static boolean gameOver = false;
    
    private static BufferedReader stdin;


    //--------------------------------------------------------------------------
    // Method Purpose:
    //    Main method. Sets up the game and passes control to the play() method 
    public static void main(String Args[]) throws IOException  {
        
        // allow input from the user
        stdin = new BufferedReader(new InputStreamReader(System.in));
        
        // display game instructions
        displayInstructions();    
        
        // get the list of words.
        wordlist = getWordList();

        // play the game
        while (!gameOver) {
            gameOver = playGame();
        }
        
        // display final message
        displayFinalMessage();
        
        
    }  // method:main
    //--------------------------------------------------------------------------    
    
    //-----------------------------------------------------------------------------------------------
    // Method Purpose:
    //    To present instructions to the user on how the game is played
    private static void displayInstructions() {
    	System.out.println("******************************************************************");
    	System.out.println("*                   Welcome to Word Jumble                       *");
    	System.out.println("******************************************************************");
    	System.out.println("*                                                                *");
    	System.out.println("* Instructions:                                                  *");
    	System.out.println("*     You will be presented with a jumbled word. You are given a *");
    	System.out.println("* certain number of chances to guess the original word. This is  *");
    	System.out.println("* represented as your 'Life'. Your score will increase every     *");
    	System.out.println("* time you correctly guess a word.                               *");
    	System.out.println("*                                                                *");
    	System.out.println("* You may Quit the game at any time by typing 'Q'.               *");
    	System.out.println("*                                                                *");
    	System.out.println("******************************************************************");
    	System.out.println("");
    
    } // method:displayInstructions
    //-----------------------------------------------------------------------------------------------
    
    
    //--------------------------------------------------------------------------
    // Method Purpose:
    //    Returns an <ARRAY> filled with different words 
    private static String[] getWordList() {
    	
        String[] mywords = {"hello", "what", "carl", "thomas"};
        return mywords;
    } // method getWordList
    //--------------------------------------------------------------------------
    
    
    
    //-----------------------------------------------------------------------------------------------
    // Method Purpose:
    //    To control gameplay based on rules, and to determine a winner.
    private static boolean playGame() throws IOException  {
        String userGuess;
        
        
        // get a random word
        randomWord  = getRandomWord();
        
        // jumble the word
        jumbleWord  = getJumbleWord(randomWord);
        
        // display the jumbled word to the user & prompt for a guess
        System.out.println("The letters are: " + jumbleWord);
        
        
        // until we have a winner or we're out of life
        while ((!isWinner) || (life > 0)) {
            
            // get the user's geuss
            userGuess = getGuess();
            
            // see if they quit
            if (checkQuit(userGuess)) {
                gameOver = true;
                break;
            }
            // see if they've won
            if (checkWin(userGuess, randomWord)) {
                isWinner = true;
                score++;
                break;
            } else {
            	
            	// if we're here, we have a bad guess.
            	life--;
            	
            	// if we're out of life...
            	if (life == 0) {
            	
            	    // display a message
                    System.out.println(" I'm sorry. But that guess was also incorrect. You have 0 life left.");
                    System.out.print(" Would you like to try again? (y/n)  :");
                    
                    // see if user wants to play again
                    if (stdin.readLine().equalsIgnoreCase("n")) {
                    	break;
                    } else {
                       
                       // restart
                       life = 5;
                       System.out.println("");
                       System.out.println("");
                       System.out.println("");
                       System.out.println("");
                       displayInstructions();
                       playGame();	
                    }
                    	
                } else {
                    System.out.print("   -- Incorrect Guess");
                    System.out.println("                Score: " + score + " | Life: " + life);
                    System.out.println("");
                } // if life=0
            
            } // if not a winner
        
        } // while still playing
        
        
        // if the user guessed correctly...
        if (isWinner) {
        
            // disply a message
            System.out.println("**********************************************************");
            System.out.print("CONGRATULATIONS!!! You got it right! Next Word? (y/n):  ");
            
            // see if we should play again
            if (stdin.readLine().equalsIgnoreCase("y")) {
                isWinner = false;
                playGame();
            } else {
                return true;
            }
        }
        
        return true;
    } // method:playGame()
    //-----------------------------------------------------------------------------------------------
    
   
    
    //--------------------------------------------------------------------------
    // Method Purpose:
    //    Get a random word from an array of words
    private static String getRandomWord() {
        num = new Random();
        return wordlist[ (Math.abs (num.nextInt()) %wordlist.length) ];
    } // method:getRandomWord
    //--------------------------------------------------------------------------
    
    
    //--------------------------------------------------------------------------
    // Method Purpose:
    //    To randomize the letters in a word and return a <STRING> value
    private static String getJumbleWord(String wordToJumble) {
    	
    	// the size of the word / arrays we'll use
    	int wordSize = wordToJumble.length();
    	
    	// a randum number
    	int randNum;
    	
    	// an array to hold the letters of the jumbled word
    	String[] jumbledLetters  = new String[wordSize];
    	
    	// the returned string of jumbled characters
    	String jumbledWord = "";
    	    	
    	// holds value of current letter during loop
    	String temp;
    	
    	// fill array with letters from wordToJumble
    	for (int i=0; i< wordSize; i++) {
           jumbledLetters[i] = wordToJumble.substring(i,i+1);
        }
        
        // Iterate through jumbled letters, and swap letter @ iterative
        // location with letter from randomNumber location.
        for (int i=0; i < wordSize; i++) {
            randNum = (Math.abs (num.nextInt()) %wordSize);
            temp = jumbledLetters[i];
            jumbledLetters[i] = jumbledLetters[randNum];
            jumbledLetters[randNum] = temp;
        }
        
        // generate a string from the array of letters
        for (int i=0; i< wordSize; i++) {
           jumbledWord += jumbledLetters[i];
        }
        
        // return the string
        return jumbledWord;
        
    } // method:getJumbleWord
    //--------------------------------------------------------------------------


    
    //--------------------------------------------------------------------------
    // Method Purpose:
    //    To get a <STRING> guess from the user
    private static String getGuess() throws IOException {
    	
        try {
            //read the string in from the user
            System.out.print("Please enter your guess: ");
    	    return stdin.readLine();
        } catch(IOException e) { 
            System.out.println("Something went wrong with the input"); 
            return "error";
        }
        
    } // method:getGuess
    //--------------------------------------------------------------------------
    
    
    
    
    //---------------------------------------------------
    // Method Purpose:
    //    To determine if the user wants to Quit or not.
    private static boolean checkQuit(String userGuess) {
        if (userGuess.equalsIgnoreCase("Q")) {
            return true;
        } else {
            return false;
        }
    } // method:checkQuit
    //---------------------------------------------------
    
    
    
    
    //---------------------------------------------------
    // Method Purpose:
    //    Determine if user guessed correct word
    private static boolean checkWin(String userGuess, String randomWord) {
        if (userGuess.equalsIgnoreCase(randomWord)) {
            return true;
        } else { 
            return false;
        }
        
    } // method:checkWin
    //---------------------------------------------------
    
    
    //--------------------------------------------------------------------------------------------
    // Method Purpose:
    //    Display the final message
    private static void displayFinalMessage() {
         System.out.println("");
         System.out.println("");
         System.out.println("");
         System.out.println("");
         System.out.println("");
         System.out.println("***********************************************************");
         System.out.println("               Thank you for Playing!!!                    ");
         System.out.println("");
         System.out.println("Final Score: " + score);
         System.out.println("");
         System.out.println("");
         
    } // method:displayFinalMessage
    //--------------------------------------------------------------------------------------------
    
    
    
} // class:WordJumble

I did a few things different, but the idea is the same. Take a look at the "playGame()" method.

Let me know if you have any questions!


hth,
-Celt

Last edited by Celtboy; 01-09-2005 at 03:47 AM..
Celtboy is offline   Reply With Quote
Old 01-09-2005, 03:54 AM   PM User | #6
Celtboy
Regular Coder

 
Join Date: May 2002
Location: Virginia, USA
Posts: 620
Thanks: 0
Thanked 6 Times in 6 Posts
Celtboy is an unknown quantity at this point
Celtgirl pointed out to me that my implementation seems more like an opportunity to "show off" than to help, and I'm really sorry if I came across that way! It was not my intent!!!

The way you are doing it is perfectly fine! My main suggestion would be:

1) use methods similar to mine to create the jumbled words. I just think you'll find it easier. Not that there is anything wrong with the way you are doing it!!! I just thought it could get annoying to have to keep up with the words in two different places like that!!!


Other than that, keep at it!!!

-Celt
Celtboy is offline   Reply With Quote
Old 01-09-2005, 08:24 AM   PM User | #7
cwl157
New Coder

 
Join Date: Jun 2003
Posts: 92
Thanks: 0
Thanked 0 Times in 0 Posts
cwl157 is an unknown quantity at this point
i know your not trying to show off at all. I have only had a semester of java and thats the only programming ive had so whatever tips i can get to make it easier or make me more effiecent is very welcomed at this point.
cwl157 is offline   Reply With Quote
Old 01-09-2005, 08:54 AM   PM User | #8
shmoove
Regular Coder

 
Join Date: Dec 2003
Posts: 367
Thanks: 0
Thanked 0 Times in 0 Posts
shmoove is an unknown quantity at this point
Quote:
Originally Posted by Celtboy
Celtgirl pointed out to me that my implementation seems more like an opportunity to "show off" than to help, and I'm really sorry if I came across that way! It was not my intent!!!
Whipped! (j/k)

shmoove
shmoove is offline   Reply With Quote
Old 02-09-2005, 02:48 AM   PM User | #9
JWizard
New Coder

 
Join Date: Feb 2005
Posts: 27
Thanks: 0
Thanked 0 Times in 0 Posts
JWizard is an unknown quantity at this point
That's 100 times longer than it has to be. The first actual line of code is on the 97th line! Also, who the heck taught you to comment like that? Have you ever used the Javadoc utility?. I just spit out my coffee laughing, you made my day. I've quite possibly never seen anything so amusing in my life. I recently finished writing a multi-threaded IRC client in about the same number of lines.
Keep up the good work
JWizard is offline   Reply With Quote
Old 02-09-2005, 04:40 AM   PM User | #10
WA
Administrator


 
Join Date: Mar 2002
Posts: 2,596
Thanks: 2
Thanked 19 Times in 18 Posts
WA will become famous soon enough
JWizard, there is absolutely no reason to be condescending when posting. Please keep that in mind when posting in the future.
__________________
- George
- JavaScript Kit- JavaScript tutorials and 400+ scripts!
- JavaScript Reference- JavaScript reference you can relate to.
WA is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 11:39 AM.


Advertisement
Log in to turn off these ads.