Results 1 to 6 of 6
  1. #1
    cachi is offline Member
    Join Date
    Jul 2007
    Posts
    40
    Rep Power
    0

    Default Help, loop with java

    Hi, 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 I'm not sure about how to make it run through more then once i know i need a loop but I'm not sure where to put it.

    Java 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 letters 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;
       }
     }
       
    }
    Thanks.

  2. #2
    Sircedric88 is offline Member
    Join Date
    Jul 2007
    Location
    Las Vegas
    Posts
    14
    Rep Power
    0

    Default

    Hey, I have been having the same problem with a program where there is an index of games to choose from, and I want it to loop as long as the user input is equal to y or if they want to return to the index.
    I tried while loops, for loops, do while. Nothing seemed to work. I hope an advanced member can help.

    I was reading over your code, and I realized that your syntax is very old. You used a string buffer, and all that other jazz for user input. I think you should download the JDK 5.0. It is much easier to get input with a Scanner Class. (It can also read files and such) I would highly recommend it!

    here's my code. It won't run for you unless you have the JDK 5.-
    Java Code:
    import java.util.Scanner;
    
    
    public class Program {
    
    	public static void main(String[] args) {
    	Scanner s = new Scanner(System.in);
    	System.out.println("Please enter your first and last name");
    	String first = s.next();
    	String second = s.next();
    	System.out.println("Welcome " + first + " " + second);
    
    	System.out.println("What game would you like to play? (Enter corresponding number)");
    	System.out.println("1. Guessing game");
    	Scanner game = new Scanner(System.in);
    	int playGame = game.nextInt();
    	
    	if (playGame==1)
    	{
    	System.out.println("You have chosen the guessing game!");
    
       // runs guess game
    	String playAgain = "y";
    	
    	do
    	{
    	guessGame();
    	System.out.println("Would you like to play again? (y/n)");
    	Scanner again = new Scanner(System.in);
    	String encore = again.next();
    	playAgain = encore;
    	} while (playAgain == "y");	
    	
    	}
    }
    	
    	public static void guessGame()
    	{
    		
    		System.out.println("Pick a number 1 - 10");
    		int target = (int) (Math.random()*10);
    		System.out.print("Here's a hint: ");
    		
    		if (target <= 5)
    		{
    			System.out.println("The taget is less than or equal to 5");
    		}
    		else
    		{
    			System.out.println("The target is greater than or equal to 6");
    		}
    		Scanner playerGuess = new Scanner(System.in);
    		int guess = playerGuess.nextInt();
    		if (guess == target)
    		{
    			System.out.println("We have a Winner!");
    		}
    		else
    		{
    			System.out.println("Sorry, please try again");
    			System.out.println("The target was " + target);
    		}
    
    	
    		
    	}
    
    }

  3. #3
    yiweiang is offline Member
    Join Date
    Aug 2007
    Posts
    15
    Rep Power
    0

    Post

    Hi there,

    If i were to do it, i would create another class with a method run() that returns a integer. Now i can get the main method to create an instance of this class.Create a loop that will call the method run().

    public static void main(string Args[])
    {

    Game myGame=new Game();
    while(x==0)
    {
    myGame.run();
    }
    }


    ********

    public class Game()
    {

    public int run()
    {

    //your code goes here. This code below runs after the game completes

    System.out.println("Would you like to play again?" 0 for yes, 1 for no)
    int decision=myInput.nextInt(); //remember to import Scanner method

    return decision;
    }
    }
    When the method run completes, you decide in the programming logic for it to return either 1 or 0.



    So if it's zero, it runs again. Otherwise it stops.

  4. #4
    Sircedric88 is offline Member
    Join Date
    Jul 2007
    Location
    Las Vegas
    Posts
    14
    Rep Power
    0

    Default

    hey, thanks you for replying to my question. I was wondering about you Game object or class if you were assuming that it had been previously initialized, or you forgot. Sorry I'm jw.

    So you're saying use the run class on game. Ok Gotcha!
    But why would you make it a new class, and not just another method? i know it's to apply it to that specific game but, would it work differently as a method?

    Ok well as you can see in my code, my guessing game is just another method. So would it work to say:
    while (x==0)
    {
    guessGame.run();
    }

    sorry this whole concept of methods and classes is new to me

  5. #5
    yiweiang is offline Member
    Join Date
    Aug 2007
    Posts
    15
    Rep Power
    0

    Default

    Hi there,

    First of all, creating a method in the same class would work the same way. I just didn't think of that : ) This is the reason why i didnt just put it in a method in the same class.

    The whole idea of object oriented programming is that you have one class that can be used over and over again, so the core of your game should be in one class, called the Game class; and the other class that has the main method can be the GameTest method (what programmers usually call it).

    So to use the contents in the Game class, you go to the GameTest class and create an instance of the Game class:

    Game myGame=new Game();

    After that, you can use the run() method.

    However, you can also use what you suggested. To create a method under the main method, and have a loop in the main method that calls the run() method underneath.

  6. #6
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    9

    Default

    Java Code:
      public static void main(String Args[])
      {
        //instructions for player
        System.out.println("Try to unscramble the words!!  All letters are in lower case.");
    
        int score = 0;               //goes up if right
        int life = 5;                //goes down if wrong
    
        //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 = "";
        boolean goMore = true;
    
        try
        {
            while(goMore)
            {
                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
                //read the string in from the user
                System.out.print("Please enter your guess: ");
    	      line = (console.readLine());
    
                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);
                }
    
                System.out.println("More? \"y\" or \"n\"");
                line = console.readLine().trim();
                goMore = line.equals("y");
            }
            console.close();
        }
        catch(IOException e) 
        { 
            System.out.println("Something went wrong with the input");
            goMore = false;
        }
      }

Similar Threads

  1. Loop Help
    By HeavyD in forum New To Java
    Replies: 7
    Last Post: 09-22-2010, 10:55 PM
  2. Replies: 0
    Last Post: 11-14-2007, 04:22 PM
  3. Help with loop in java
    By trill in forum New To Java
    Replies: 1
    Last Post: 08-07-2007, 08:36 AM
  4. Enhanced For loop In Java
    By goldhouse in forum Advanced Java
    Replies: 1
    Last Post: 05-06-2007, 05:26 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •