Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 18 of 18

Thread: Assigning random int to strings

  1. #1
    Junior Member
    Join Date
    Jun 2014
    Posts
    16
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Assigning random int to strings

    .
    Last edited by emilysk8; June 16th, 2014 at 02:50 PM.


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,190
    Thanks
    49
    Thanked 2,172 Times in 2,145 Posts

    Default Re: Assigning random int to strings

    what ISN'T working...
    Please explain? If there are error messages, copy the full text and paste it here.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Jun 2014
    Posts
    16
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Assigning random int to strings

    Oh my heck, sorry! Let me try this again. Editing my first post is just not going to happen.

    I think my loop is broken.

          while (gamesPlayed<gameQty)
          {
             userChoice = JOptionPane.showInputDialog("Rock, Paper, or Scissors?");
     
             //Determine winner for each game
             if (compChoice.equalsIgnoreCase(userChoice));
             {
                userChoice = JOptionPane.showInputDialog("Tie, game not counted. Rock, Paper, or Scissors?");
                ties++;
             }
     
             if ((compChoice == "Rock") && (userChoice == "Paper"));
             {
                JOptionPane.showInputDialog("Computer chose rock, you lose. Try again.");
                compWins++;
                gamesPlayed++;

    It seems to circle through the loop gameQty times, without comparing.

  4. #4
    Member
    Join Date
    Jul 2013
    Location
    Europe
    Posts
    477
    Thanks
    0
    Thanked 92 Times in 77 Posts

    Default Re: Assigning random int to strings

    If you want to have a loop run for a certain number of times prefer a for-loop over a while-loop.

    Example of a for-loop running 17 times:
    int a = 17;
    for (int i = 0; i < a; i++) {
    }

    Furthermore, dont use "==" to compare Strings, use the "equals" method.

  5. The Following User Says Thank You to Cornix For This Useful Post:

    emilysk8 (June 16th, 2014)

  6. #5
    Junior Member
    Join Date
    Jun 2014
    Posts
    16
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Assigning random int to strings

    Thank you Cornix! Changed it to a for-loop, and .equals to compare. Program runs, but with a few issues:
    - Looping through more times than user enters.
    - I don't think the computer is choosing, or my comparisons are still broken.

          //loop for gameQty
          for (int qty=gameQty; gamesPlayed<qty; gamesPlayed++)
          {
             userChoice = JOptionPane.showInputDialog("Rock, Paper, or Scissors?");
     
             //Determine winner for each game
             if (compChoice.equalsIgnoreCase(userChoice));
             {
                userChoice = JOptionPane.showInputDialog("Tie, game not counted. Rock, Paper, or Scissors?");
                ties++;
             }
     
             if ((compChoice == "Rock") && (userChoice == "Paper"));
             {
                JOptionPane.showInputDialog("Computer chose rock, you win. Try again.");
                userWins++;
                gamesPlayed++;
             }
     
             if ((compChoice == "Rock") && (userChoice == "Scissors"));
             {
                JOptionPane.showInputDialog("Computer chose rock, you lose. Try again.");
                compWins++;
                gamesPlayed++;
             }
     
          }

  7. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,190
    Thanks
    49
    Thanked 2,172 Times in 2,145 Posts

    Default Re: Assigning random int to strings

    The code should use the equals() method for comparing Strings, NOT the == operator.
    If you don't understand my answer, don't ignore it, ask a question.

  8. #7
    Junior Member
    Join Date
    Jun 2014
    Posts
    16
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Assigning random int to strings

    Oops. Like this? From here, it cannot find the symbol, how do I let the user lose/win/tie, then enter a new variable for userChoice?

          //loop for gameQty
          for (int qty=gameQty; gamesPlayed<qty; gamesPlayed++)
          {
             userChoice = JOptionPane.showInputDialog("Rock, Paper, or Scissors?");
     
             //Determine winner for each game
             if (compChoice.equalsIgnoreCase(userChoice));
             {
                userChoice = JOptionPane.showInputDialog("Tie, game not counted. Rock, Paper, or Scissors?");
                ties++;
             }
     
             if (compChoice.equalsIgnoreCase("Rock"));
             {
     
                if (userChoice.equalsIgnoreCase("Paper"));
                {
                JOptionPane.showInputDialog("Computer chose rock, you win.");
                userchoice = JOptionPane.showInputDialog("Try again.");
                userWins++;
                gamesPlayed++;
                }
     
                if (userChoice.equalsIgnoreCase("Scissors"));
                {
                JOptionPane.showInputDialog("Computer chose rock, you lose.");
                userchoice = JOptionPane.showInputDialog("Try again.");
                compWins++;
                gamesPlayed++;
                }
             }

  9. #8
    Member
    Join Date
    Jul 2013
    Location
    Europe
    Posts
    477
    Thanks
    0
    Thanked 92 Times in 77 Posts

    Default Re: Assigning random int to strings

    1) The for loop looks quite complicated and non-standard.
    You should try to stick with the established standards to make the code easier readable by others (like us).
    Usually a for-loop looks like this:
    for (INIT_LOOP_VAR; LOOP_CONDITION; MANIPULATE_LOOP_VAR)
    for example:
    for (int round = 0; round < maxRounds; round++)
    Your example looks like this:
    for (INIT_UPPER_BOUNDS; LOOP_CONDITION; MANIPULATE_LOOP_VAR)
    and it is hard for us because we
    a) dont know how the loop variable (in your case gamesPlayed) is initialized.
    b) dont know how the upper bounds (in your case gameQty) is initialized.

    So we practically dont know anything about what is going on there.


    2)
    You still use "==" to compare your strings, namely at:
    if ((compChoice == "Rock") && (userChoice == "Paper"));
    this should not work. Use the "equals" or "equalsIgnoreCase" method here as well.


    3)
    You can also add "System.out.println(...)" statements in your code to print out the contents of your variables and/or the control flow of the program.
    These might help you to find out where the problem is. For example, you could find out why the comparisons fail; maybe one of the variables is initialized with a bad value?

  10. The Following User Says Thank You to Cornix For This Useful Post:

    emilysk8 (June 17th, 2014)

  11. #9
    Junior Member
    Join Date
    Jun 2014
    Posts
    16
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Assigning random int to strings

    Does System.out.println(...) work where I'm using the more visual JOptionPane ...?

    --- Update ---

    System.out.println isn't displaying anything.

    Here is all of the code.

    /*
    Rock Paper Scissors
     
    Emily Caraballo
    */
     
    import javax.swing.JOptionPane;
    import java.util.Random;
     
    public class RockPaperScissors
    {
      public static void main(String[] args)
      {
          JOptionPane.showMessageDialog(null, "Welcome to Rock, Paper, Scissors");
     
          Random rand = new Random(); 
          int compRand = rand.nextInt(3);  // Random Number Generated for computer choice
          String compChoice = " ";    // Computer Choice assigned, based on int compRand
          String userChoice;          // User Choice
          int gamesPlayed = 0;        // Number of games played
          int compWins = 0;           // Number of computer wins
          int userWins = 0;           // Number of user wins
          int ties = 0;               // Number tied games
          int gameQty;                //number of games to play
          gameQty = Integer.parseInt(JOptionPane.showInputDialog("How many games do you want to play?"));
     
          //make sure number of games is odd
          if (gameQty % 2 == 0)
          {
             gameQty = Integer.parseInt(JOptionPane.showInputDialog("Please enter an odd number. How many games do you want to play?"));
          }
     
          //assigns computer choice to r,p,s
       	if	(compRand == 0)
       	{
       		compChoice.equals("Rock");
       	}
     
       	if	(compRand == 1)
       	{
       		compChoice.equals("Paper");
       	}
     
       	if	(compRand == 2)
       	{
       		compChoice.equals("Scissors");
       	}
     
          System.out.println(compChoice);
     
          //loop for gameQty
          for (int gamesPlayed; gamesPlayed<gameQty; gamesPlayed++)
          {
             userChoice = JOptionPane.showInputDialog("Rock, Paper, or Scissors?");
     
             //Determine winner for each game
             if (compChoice.equalsIgnoreCase(userChoice));
             {
                userChoice = JOptionPane.showInputDialog("Tie, game not counted. Rock, Paper, or Scissors?");
                ties++;
             }
     
             if (compChoice.equalsIgnoreCase("Rock"));
             {
     
                if (userChoice.equalsIgnoreCase("Paper"));
                {
                JOptionPane.showInputDialog("Computer chose rock, you win.");
                userchoice = JOptionPane.showInputDialog("Try again.");
                userWins++;
                gamesPlayed++;
                }
     
                if (userChoice.equalsIgnoreCase("Scissors"));
                {
                JOptionPane.showInputDialog("Computer chose rock, you lose.");
                userchoice = JOptionPane.showInputDialog("Try again.");
                compWins++;
                gamesPlayed++;
                }
             }
     
     
          }
     
     
      }  //end main
    } //end class

    Here are my errors:

    RockPaperScissors.java:52: error: variable gamesPlayed is already defined in method main(String[])
          for (int gamesPlayed; gamesPlayed<gameQty; gamesPlayed++)
                   ^
    RockPaperScissors.java:69: error: cannot find symbol
                userchoice = JOptionPane.showInputDialog("Try again.");

  12. #10
    Member
    Join Date
    Jul 2013
    Location
    Europe
    Posts
    477
    Thanks
    0
    Thanked 92 Times in 77 Posts

    Default Re: Assigning random int to strings

    System.out.println(...) will write to the default Output unless you specify a different output stream for it.
    So by default it will write to the console window. If you are starting from an IDE there is probably some way of showing the console during the program execution.

    Besides that you could also abuse a JOptionPane to output the values if you want to be lazy or just cant find a way to access the console.



    Your error about the "gamesPlayed" variable comes because you define it twice.
    At the very beginning of your program you have this line:
    int gamesPlayed = 0;
    then, in your for-loop you have this:
    for (int gamesPlayed; gamesPlayed<gameQty; gamesPlayed++)
    your compiler is telling you that you have the same variable twice. This is not allowed.

    You can either remove the first line at the top (which I would recommend) or if you want to keep it you can remove the "int" from the for-loop:
    for (gamesPlayed; gamesPlayed<gameQty; gamesPlayed++)

  13. #11
    Junior Member
    Join Date
    Jun 2014
    Posts
    16
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Assigning random int to strings

    Gotcha! So using the JOptionPane to display computer choice, it displays nothing. I'm assuming there is nothing stored in the variable, then, right? So maybe some of this code is wrong??

          Random rand = new Random(); 
          int compRand = rand.nextInt(3);  // Random Number Generated for computer choice
          String compChoice = " ";    // Computer Choice assigned, based on int compRand
     
          //assigns computer choice to r,p,s
       	if	(compRand == 0)
       	{
       		compChoice.equals("Rock");
       	}
    // etc... for paper & scissors
    Last edited by Norm; June 17th, 2014 at 02:37 PM. Reason: Removed spaces in highlight tag

  14. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,190
    Thanks
    49
    Thanked 2,172 Times in 2,145 Posts

    Default Re: Assigning random int to strings

    The equals() method is used to compare two Strings and returns a boolean value: true or false. The posted code doesn't look at what is returned.

    The code looks like it should be using an assignment statement.
    If you don't understand my answer, don't ignore it, ask a question.

  15. #13
    Junior Member
    Join Date
    Jun 2014
    Posts
    16
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Assigning random int to strings

    /*
    Rock Paper Scissors
     
    Emily Caraballo
    */
     
    import javax.swing.JOptionPane;
    import java.util.Random;
     
    public class RockPaperScissors
    {
      public static void main(String[] args)
      {
          JOptionPane.showMessageDialog(null, "Welcome to Rock, Paper, Scissors");
     
          Random rand = new Random(); 
          int compRand = rand.nextInt(3);  // Random Number Generated for computer choice
          String compChoice = " ";    // Computer Choice assigned, based on int compRand
          String userChoice;          // User Choice
          int compWins = 0;           // Number of computer wins
          int userWins = 0;           // Number of user wins
          int ties = 0;               // Number tied games
          int gameQty;                //number of games to play
          gameQty = Integer.parseInt(JOptionPane.showInputDialog("How many games do you want to play?"));
     
          //make sure number of games is odd
          if (gameQty % 2 == 0)
          {
             gameQty = Integer.parseInt(JOptionPane.showInputDialog("Please enter an odd number. How many games do you want to play?"));
          }
     
          //assigns computer choice to r,p,s
       	if	(compRand == 0)
       	{
       		compChoice.equals("Rock");
       	}
     
       	if	(compRand == 1)
       	{
       		compChoice.equals("Paper");
       	}
     
       	if	(compRand == 2)
       	{
       		compChoice.equals("Scissors");
       	}
     
          JOptionPane.showMessageDialog(null, compChoice);      // Is the computer choosing??? NO. :(
     
          //loop for gameQty
          for (int gamesPlayed; gamesPlayed<gameQty; gamesPlayed++)
          {
             userChoice = JOptionPane.showInputDialog("Rock, Paper, or Scissors?");
     
             //Determine winner for each game
             if (compChoice.equalsIgnoreCase(userChoice));
             {
                userChoice = JOptionPane.showInputDialog("Tie, game not counted. Rock, Paper, or Scissors?");
                ties++;
             }
     
             if (compChoice.equalsIgnoreCase("Rock"));
             {
     
                if (userChoice.equalsIgnoreCase("Paper"));
                {
                JOptionPane.showInputDialog("Computer chose rock, you win.");
                userchoice = JOptionPane.showInputDialog("Try again.");
                userWins++;
                gamesPlayed++;
                }
     
                if (userChoice.equalsIgnoreCase("Scissors"));
                {
                JOptionPane.showInputDialog("Computer chose rock, you lose.");
                userchoice = JOptionPane.showInputDialog("Try again.");
                compWins++;
                gamesPlayed++;
                }
             }
     
     
          }
     
          // Determine Grand Winner
          // If compWins > userWins, display "Computer Wins."
          // If userWins > compWins, display "You win!" 
          // Java is really hard, my brain is being stretched. It's also rewarding when I finally get it to work!!
     
        }  //end main
    } //end class

  16. #14
    Member
    Join Date
    Jul 2013
    Location
    Europe
    Posts
    477
    Thanks
    0
    Thanked 92 Times in 77 Posts

    Default Re: Assigning random int to strings

    What Norm means is that you have to do:
    compChoice = "something";
    to assign a value to it.

    The equals method is only supposed to be used for conditional branches in your code. (if, while, etc)

  17. #15
    Junior Member
    Join Date
    Jun 2014
    Posts
    16
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Assigning random int to strings

    Thanks for your help & patience. I will get better at this.

    Got it, .equals compares, = assigns, what does == do? Does it compare outside of conditional branches?
    And yay! Computer is choosing!

    Now, loop is somehow wrong still. How does user assign new value to userChoice after a tie/win/loss?
    Last edited by emilysk8; June 17th, 2014 at 03:11 PM.

  18. #16
    Member
    Join Date
    Jul 2013
    Location
    Europe
    Posts
    477
    Thanks
    0
    Thanked 92 Times in 77 Posts

    Default Re: Assigning random int to strings

    The "==" operator is comparing references or primitive data types.
    The "equals" method compares equality of objects based on the logic defined in the class.

    For example:
    String a = "Test";
    String b = a;
    System.out.println(a == b); // => returns true!
    Because here we have 2 String variables "a" and "b", but both are referencing the same String object.

    But in this scenario:
    String a = "Test";
    String b = "Test";
    System.out.println(a == b); // => returns false!
    We have 2 String variables "a" and "b", but both are referencing 2 different String objects which just happen to hold the same contents.

    In general you should always use "equals" whenever you are working with objects. Only in very few cases the == operator should be used.
    But when working with non-object variables, that is primitive data types, you need to use == because the equals method does not exist for these.
    For example int, float, long, double, char, boolean, etc. These are all primitive.

  19. #17
    Junior Member
    Join Date
    Jun 2014
    Posts
    16
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Assigning random int to strings

    Not sure what this error means?
    The top part seems to be working now. Issues with the loop now. Here is the error. I can post the full code again if needed? Thought it's a couple threads above this...

    RockPaperScissors.java:68: error: cannot find symbol
                userchoice = JOptionPane.showInputDialog("Try again.");
                ^

  20. #18
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,190
    Thanks
    49
    Thanked 2,172 Times in 2,145 Posts

    Default Re: Assigning random int to strings

    error: cannot find symbol
    The compiler can not find a definition for the symbol named in the error message that is in scope (within the same {}s) where that symbol is being used.
    class A_Class {
       int classVar; // define at class level;  in Scope for all methods
     
       void meth1() {
           int aVar;    // define aVar; in Scope only within meth1
           //  classVar in Scope here
           //...
       } // end meth1()
     
       void meth2() {
           //  aVar in NOT in SCOPE here
           //  classVar in Scope here
           //...
       } //  end meth2()
    } // end class
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. RANDOM int
    By Rinor in forum What's Wrong With My Code?
    Replies: 2
    Last Post: January 8th, 2014, 10:29 AM
  2. Assigning Colors in a 2D array in a random order
    By captain in forum Object Oriented Programming
    Replies: 5
    Last Post: February 21st, 2012, 06:13 AM
  3. Assigning an 'int' from a JTextField to a variable...
    By RiskyShenanigan in forum What's Wrong With My Code?
    Replies: 4
    Last Post: March 26th, 2011, 04:00 PM
  4. Returning Random Strings from an Array
    By cfmonster in forum Collections and Generics
    Replies: 3
    Last Post: September 8th, 2009, 11:13 PM