我正在尝试创建一个程序,从文件中选择一个随机单词,并根据单词的长度输出正确数量的空格。例如,如果单词是智能的,则程序输出_ _ _ _ _。这是该计划:
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();
}
}
这就是错误:
java:18: error: cannot find symbol
int selected = r.nextInt[100];
^
symbol: variable nextInt
location: variable r of type Random
1 error
非常感谢任何有助于理解我未正确行事的帮助。
答案 0 :(得分:3)
int selected = r.nextInt[100];// use () r.nextInt(num);
答案 1 :(得分:1)
int selected = r.nextInt[100];
你的问题在这里,你试图像数组一样访问变量nextInt,但它是一个函数。
正确的方法是:
int selected = r.nextInt(100);
您使用括号,因为您将值100作为参数传递。
答案 2 :(得分:0)
很抱歉由于某些原因,这里的格式对我不起作用
你有
int selected = r.nextInt[100];
代码应该是
int selected = r.nextInt(100);
原因是您使用[]表示数组,()来调用对象上的方法。
例如,
如果你想创建一个数组,你可以
int [] arr = new int [100]; //创建了一个具有足够存储空间的数组来保存100 int
以下内容将失败
int() arr = new int(arr); // fail!
另一方面,
如果你这样做
Random r = new Random(); // it works!
但以下会失败
Random r = new Random[]; // fail!