...

View Full Version : looping in java help



cwl157
01-07-2005, 11:52 PM
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


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;
}
}

}

turbowrx
01-08-2005, 02:02 AM
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.

Celtboy
01-08-2005, 04:03 AM
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

cwl157
01-08-2005, 06:22 PM
yea if its not that big of a trouble for you and you want to you can write an example. Thanks

Celtboy
01-08-2005, 09:30 PM
Here's my implementation of the game:


/**************************************************************************************

>--------------------------------------------<
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

Celtboy
01-09-2005, 03:54 AM
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!!! :eek:

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!!! :thumbsup:

-Celt

cwl157
01-09-2005, 08:24 AM
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.

shmoove
01-09-2005, 08:54 AM
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!!! :eek:
Whipped! (j/k) ;)

shmoove

JWizard
02-09-2005, 02:48 AM
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

WA
02-09-2005, 04:40 AM
JWizard, there is absolutely no reason to be condescending when posting. Please keep that in mind when posting in the future.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum