Page 1 of 2 12 LastLast
Results 1 to 20 of 22
  1. #1
    Franneldort is offline Member
    Join Date
    Oct 2008
    Posts
    19
    Rep Power
    0

    Default How to get a random value in an array

    I'm setting up a hangman game with 20 words stored in an array. I don't know how to select a random word from the array though. I've tried it with math.random() but it's not taking... Any help would be great. Attached is my current program with the getNewWord().
    Attached Files Attached Files

  2. #2
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,338
    Rep Power
    25

    Default

    but it's not taking.
    Can you explain what happens, why it is incorrect and what you want to change it to?
    Use a Random method to get an integer in the range 0 to 19 (nbr words -1) and use that integer as an index into the array.

  3. #3
    Franneldort is offline Member
    Join Date
    Oct 2008
    Posts
    19
    Rep Power
    0

    Default

    Right now, it's not doing anything, because of my syntax. I don't know how to make it do what I would like, and that is what you said, which is, getting a random number between 1-20 and putting that number into the array to select a word equal to that number.

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

    Default

    Java Code:
    public class HangmanPanel2
        ...
        Random rand = new Random();
        ...
        public String getNextWord() {
            int n = seed.nextInt(dictionary.length);
            return dictionary[n];
        }
        ...

  5. #5
    Franneldort is offline Member
    Join Date
    Oct 2008
    Posts
    19
    Rep Power
    0

    Default

    hmmm...do I need a String dictionary parameter for the getNextWord() ? It's giving me syntax errors for "seed" and both "dictionary terms" as well as in the blank parameters for the method.

    Java Code:
    private String getNextWord() {
    		int n = [B]seed[/B].nextInt([B]dictionary[/B].length);
    		return [B]dictionary[/B][n];	 
    	}

  6. #6
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,338
    Rep Power
    25

    Default

    It's giving me syntax errors
    Please copy and post the full text of the errors.

  7. #7
    Franneldort is offline Member
    Join Date
    Oct 2008
    Posts
    19
    Rep Power
    0

    Default

    for dictionary: "dictionary cannot be resolved"
    for seed: "seed cannot be resolved"


    I'm getting red lines underneath both of these words.

  8. #8
    emceenugget is offline Senior Member
    Join Date
    Sep 2008
    Posts
    564
    Rep Power
    6

    Default

    What lines of code are these referring to. More specifically, are there even variables 'dictionary' and 'seed' within their respective scopes?

  9. #9
    Franneldort is offline Member
    Join Date
    Oct 2008
    Posts
    19
    Rep Power
    0

    Default

    private String getNextWord() {
    int n = seed.nextInt(dictionary.length);
    return dictionary[n];
    }

    the red lines for these variables in my code. Here is my whole project so far attached, which is where they referring.
    Attached Files Attached Files

  10. #10
    emceenugget is offline Senior Member
    Join Date
    Sep 2008
    Posts
    564
    Rep Power
    6

    Default

    Your getNextWord method doesn't know what "seed" and "dictionary" are because they are neither declared in the scope of the class or in the method.

    I see you created a "dictionary" string array in the method "setUpDictionary", but when the method returns, "dictionary" is no longer existent. You need to declare such variables in the scope of the class. You can still initialize within methods, though.

    As for "seed", I didn't see anything in your code using the word.

  11. #11
    Franneldort is offline Member
    Join Date
    Oct 2008
    Posts
    19
    Rep Power
    0

    Default

    Lol, ok. I instantiated dictionary and changed seed to rand, and that got rid of those errors, but now the method hangmanPanel2 is getting a red line saying it can't convert from a void to String. When I change it to a string method though I get the reverse error.

    Java Code:
    public String [B]HangmanPanel2()[/B]
    	[B]{[/B]
    		secretWord = getNextWord();
    		setUpStars();
    		buildGUI();
    		setVisible(true);
    	}
    the error reads: "This method must return a result of type String"

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

    Default

    Sorry, my mistake {pseudocode!)
    The "rand" and "seed" variable names should be the same.
    Java Code:
    //    Random rand = new Random();
        Random seed = new Random();
        ...
        public String getNextWord() {
            int n = seed.nextInt(dictionary.length);
    I thought you might use a "dictionary" String[] as an instance/member variable to keep your collection of words to select from.
    Sorry for the confusion. Carry on.

  13. #13
    Franneldort is offline Member
    Join Date
    Oct 2008
    Posts
    19
    Rep Power
    0

    Default

    well I got all the syntax errors out but I got a run-time error :(

    Java Code:
    java.lang.NullPointerException
    	at HangmanPanel2.getNextWord(HangmanPanel2.java:92)
    	at HangmanPanel2.<init>(HangmanPanel2.java:30)
    	at HangmanApplet2.init(HangmanApplet2.java:11)
    	at sun.applet.AppletPanel.run(Unknown Source)
    	at java.lang.Thread.run(Unknown Source)
    line 92 is this:
    Java Code:
    int n = rand.nextInt(dictionary.length);
    		return dictionary[n] = secretWord;

  14. #14
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,338
    Rep Power
    25

    Default

    Is the variable dictionary == null or the variable rand == null?
    Either of those would give you a NPE in the code you've shown

    return dictionary[n] = secretWord;
    What is happening here? (A reference to lack of comment on the statement). It is an unusual coding.

  15. #15
    Franneldort is offline Member
    Join Date
    Oct 2008
    Posts
    19
    Rep Power
    0

    Default

    rand == null. And I am setting the array to secretWord which I use as the word for hangman. :) Am I doing that right?

  16. #16
    Franneldort is offline Member
    Join Date
    Oct 2008
    Posts
    19
    Rep Power
    0

    Default

    I'm getting a lot of run-time errors that seem to be stemming from the rand and getNextWord.

    Java Code:
    /*
     * Author: Jordan Polaniec
     * Class: EECS 1560
     * Lab:  9
     * Date: October 21, 2008
     * File: HangmanPanel.java
     * Purpose: Play a game of hangman
     */
    
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    
    public class HangmanPanel2 extends JPanel implements ActionListener {
    	private JTextField secretField;
    	private JTextField userField;
    	private JTextArea display;
    	public String secretWord;
    	public String stars;
    	public String dictionary[];
    	[I][U][B]private Random rand = new Random();[/B][/U][/I]
    	private JButton newWord;
    	private HangmanPanel2 nWord;
    	private HangmanPanel2 rWord;
    
    	public HangmanPanel2() {
    		buildGUI();
    		setVisible(true);
    		secretWord = getNextWord();
    		setUpStars();
    
    	}
    
    	public void buildGUI() {
    		// instantiate the JTextFields and display
    		newWord = new JButton(" New Word ");
    		secretField = new JTextField(10);
    		secretField.setText(stars);
    		secretField.setEditable(false);
    		userField = new JTextField(10);
    		display = new JTextArea(10, 30);
    		display.append("Guess the word. \n");
    		// add ActionListeners
    		userField.addActionListener(this);
    		// set up the layout
    		setLayout(new FlowLayout());
    		add("Center", secretField);
    		add("North", userField);
    		add("South", display);
    		add("North", newWord);
    
    		// set size of display
    		setSize(30, 100);
    		setVisible(true);
    
    	}
    
    	public void setUpDictionary() {
    		String dictionary[];
    		dictionary = new String[20];
    		dictionary[0] = new String("computer");
    		dictionary[1] = new String("outside");
    		dictionary[2] = new String("window");
    		dictionary[3] = new String("calculator");
    		dictionary[4] = new String("mouse");
    		dictionary[5] = new String("speaker");
    		dictionary[6] = new String("fish");
    		dictionary[7] = new String("screen");
    		dictionary[8] = new String("modem");
    		dictionary[9] = new String("pencil");
    		dictionary[10] = new String("pen");
    		dictionary[11] = new String("supreme");
    		dictionary[12] = new String("planet");
    		dictionary[13] = new String("immortal");
    		dictionary[14] = new String("angel");
    		dictionary[15] = new String("siege");
    		dictionary[16] = new String("command");
    		dictionary[17] = new String("mask");
    		dictionary[18] = new String("tournament");
    		dictionary[19] = new String("music");
    
    	}
    
    	/*
    	 * Pre: secretWords is instantiated with n positions 
    	 * Post: secretWords
    	 * unchanged Purpose: Returns word from random position in secretWords
    	 */
    
    	public String getNextWord() {
    		[U][I][B]int n = rand.nextInt(dictionary.length));[/B][/I][/U]
    		return dictionary[n] = secretWord;
    
    	}
    
    	/*
    	 * Pre: none Post: instance variables unchanged Purpose: Returns true if all
    	 * letters have been correctly guessed
    	 */
    	private boolean gameOver() {
    		return (secretWord.equals(stars));
    
    	}
    
    	public void setUpStars() {
    		int secretLength = secretWord.length();
    		StringBuffer result = new StringBuffer();
    		for (int k = 0; k < secretLength; k++) {
    			result.append("*");
    		}
    		stars = result.toString();
    	}
    
    	public void actionPerformed(ActionEvent e) {
    		StringBuffer secretBuffer = new StringBuffer(secretWord);
    		StringBuffer starBuffer = new StringBuffer(stars);
    		String inputStr = userField.getText();
    		char ch = inputStr.charAt(0);
    		int pos = secretWord.indexOf(ch);
    
    		if (pos == -1) {
    			display
    			.setText(" Sorry, that letter is not in the word. Try again! ");
    		}
    		else if (e.getSource() == newWord) {
    			display.append("button works");
    			[B][I][U]rWord.getNextWord();[/U][/I][/B]
    			nWord.setUpStars();
    		}
    		else {
    
    			secretBuffer.setCharAt(pos, '*');
    			secretWord = secretBuffer.toString();
    			starBuffer.setCharAt(pos, ch);
    			stars = starBuffer.toString();
    			secretField.setText(stars);
    			display.setText(" Good job! ");
    			userField.setText("");
    		}
    		if (gameOver()) {
    			display.setText(" You did it! ");
    		}
    	}
    }
    The bold lines are the ones that are giving me the errors.

    I honestly have no clue why it is giving me these run-time errors, but they are:
    java.lang.NullPointerException
    at HangmanPanel2.getNextWord(HangmanPanel2.java:92)
    at HangmanPanel2.<init>(HangmanPanel2.java:30)
    at HangmanApplet2.init(HangmanApplet2.java:10)
    at sun.applet.AppletPanel.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

    It's the rand == null that seems to be giving the error and stopping the applet from starting. Also, I don't think I'm returning the value of the dictionary array right and setting it to equal secretWord...

    Java Code:
    return dictionary[n] = secretWord;
    My attempt at setting the hidden word in the hangman game to secretWord.

  17. #17
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,338
    Rep Power
    25

    Default

    return dictionary[n] = secretWord;
    this sets the value of dictionary[n] to secretWord and returns secretWord. Is that what you want to do? What is the value of secretWord when getNextWord is called?
    I don't see how rand can be null. Its initialized when the class is created. Is that the object used at line 92 in your code?
    Are you sure its not dictionary? Put a System.out.println() in getNextWord to show the values of those two variables.

  18. #18
    Franneldort is offline Member
    Join Date
    Oct 2008
    Posts
    19
    Rep Power
    0

    Default

    I added this system.out.println to the code:

    System.out.println("this is rand" + rand + "and this is dictionary" + dictionary+ "");

    and it returned this as a value for rand and dictionary:

    "this is rand java.util.Random@e2eec8 and this is dictionarynull"

  19. #19
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    20

    Default

    On the following line, you have additional bract. Did you notice that?

    Java Code:
    int n = rand.nextInt(dictionary.length));

  20. #20
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    20

Page 1 of 2 12 LastLast

Similar Threads

  1. Array of instances using Math.random()
    By xgi1008 in forum New To Java
    Replies: 16
    Last Post: 01-25-2011, 11:10 PM
  2. Replies: 8
    Last Post: 04-19-2009, 05:50 PM
  3. Using Random
    By razmyasdfg in forum CLDC and MIDP
    Replies: 1
    Last Post: 07-27-2008, 10:47 PM
  4. random numbers without random class`
    By carlos123 in forum New To Java
    Replies: 4
    Last Post: 01-17-2008, 10:44 PM
  5. generating random numbers in a 5x5 array.
    By acidacid in forum New To Java
    Replies: 3
    Last Post: 08-14-2007, 03:44 AM

Posting Permissions

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