0

I'm attempting to create a program that selects a random word from a file and outputs the correct number of spaces depending on the length of the word. For example, if the word is smart, the program outputs _ _ _ _ _. This is the program:

    import java.util.*;
    import java.io.*;
    public class Selection {
        public static void main(String[] args) throws IOException {
        String[] words = new String[100];
        Scanner in = new Scanner(new FileReader("words.txt"));
        for (int i = 0; i < 100; i++)
                words[i] = in.next();
        Random r = new Random();
        int selected = r.nextInt[100];
        String sWord = words[selected];

        for (int j = 0; j < sWord.length(); j++)
                System.out.printf("_");

        in.close();
}
}

And this is the error:

    java:18: error: cannot find symbol
    int selected = r.nextInt[100];
                    ^
    symbol:   variable nextInt
    location: variable r of type Random
    1 error

Any help in understanding what I didn't do correctly would be greatly appreciated.

1
  • 2
    Simply change your code to this: int selected = r.nextInt(100);
    – paulsm4
    Mar 30, 2014 at 18:03

3 Answers 3

3
 int selected = r.nextInt[100];// use () r.nextInt(num);
2
  • Please let the OP know why.
    – BitNinja
    Mar 30, 2014 at 18:04
  • Like because it's a method not an array.
    – BitNinja
    Mar 30, 2014 at 18:05
1
int selected = r.nextInt[100];

Your problem is here, you are trying to access the variable nextInt like an array, but it is a function.

The correct way to do this is:

int selected = r.nextInt(100);

You use the parentheses because you are passing the value 100 as a parameter.

0

Sorry for some reasons the format here doesnt work for me

You have

int selected = r.nextInt[100];

the code should be

int selected = r.nextInt(100);

The reason being this is you use [] for array, () to call a method on an object.

For example,
if you want to create an array, you do

int[] arr = new int[100]; // created an array with enough storage to hold 100 int

the following would fail

int() arr = new int(arr); // fail!

On the other hand,
if you do

Random r = new Random(); // it works!

but the following would fail

Random r = new Random[]; // fail!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.