我正在编写代码,使用字母 a、b 和 c 生成一个随机的 3 个字母的字符串。在我创建随机变量 (Random rand = new Random();) 的那一行之后,我收到错误消息“ token 语法错误”,{预期在此 token 之后“。我不知道为什么在我看起来不错的时候会收到此错误。
我还收到错误消息:语法错误,在程序的最后一个括号之后插入“}”以完成 ClassBody。我几乎肯定我所有的右括号都匹配,所以我不知道这个错误是从哪里来的。请帮忙!!
import java.util.*;
public class Orders {
String alphabet = "abc";
ArrayList<String> list = new ArrayList<String>();
int n = alphabet.length();
Random rand = new Random();
for (int i = 0; i < 10000; i++){
char a = alphabet.charAt(rand.nextInt(n));
char b = alphabet.charAt(rand.nextInt(n));
char c = alphabet.charAt(rand.nextInt(n));
String s = Character.toString(a) + Character.toString(b) + Character.toString(c);
if(list.indexOf(s) == -1){
list.add(s);
}
}
system.out.println(arrayList);
}
最佳答案
在Java中,你不能直接在类中编写可执行语句。您需要在方法中移动代码。在方法/ block 之外只允许声明变量。只是为了测试,将所有内容移至主要方法。试试这个:
public class Orders {
public static void main(String argsp[]) {
String alphabet = "abc";
ArrayList<String> list = new ArrayList<String>();
int n = alphabet.length();
Random rand = new Random();
for (int i = 0; i < 10000; i++){
char a = alphabet.charAt(rand.nextInt(n));
char b = alphabet.charAt(rand.nextInt(n));
char c = alphabet.charAt(rand.nextInt(n));
String s = Character.toString(a) + Character.toString(b) + Character.toString(c);
if(list.indexOf(s) == -1){
list.add(s);
}
}
System.out.println(list);
}
}
注意:system.out.println(arrayList);
会抛出错误,因为没有名为arrayList
的变量,我认为是应替换为变量 list
。此外,system
应为 System
。
关于java - token ";"上的语法错误,{ 应在随机字符串创建者中的此 token 之后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18836404/