我正在尝试运行以下代码片段:
public static void findNeedles(String haystack, String[] needles){
if(needles.length > 5){
System.err.println("Too many words!");
} else {
int[] countArray = new int[needles.length];
for(int i = 0; i < needles.length;++){
String[] words = haystack.split("["'tnbfr]", 0);
for(int j = 0; j < words.length; j++){
if(words[j].compareTo(needles[i]) == 0){
countArray[i]++;
}
}
}
for(int j = 0; j < needles.length; j++){
System.out.println(needles[j] + ": " + countArray[j]);
}
}
}
知道我应该用"public static void main(String[] args) {"
包装这个
但是无法获得正确的语法。
有人帮新手入门吗?
我建议您使用类似Spring Tool Suite、Eclipse IDE或InteliJ的IDE。它们会突出显示语法错误,并提示您可能存在的问题
在告诉每个循环后如何处理变量时,忘记了在第一个for
循环中引用变量i
。你有; ++
,应该是; i++
所以要从main调用你的方法,你可以这样做:
public class YourClass {
public static void main(String[] args) {
String[] needles = new String[2];
findNeedles("some string", needles);
}
public static void findNeedles(String haystack, String[] needles){
if(needles.length > 5){
System.err.println("Too many words!");
} else {
int[] countArray = new int[needles.length];
for(int i = 0; i < needles.length; i++){
String[] words = haystack.split("["'tnbfr]", 0);
for(int j = 0; j < words.length; j++){
if(words[j].compareTo(needles[i]) == 0){
countArray[i]++;
}
}
}
for(int j = 0; j < needles.length; j++){
System.out.println(needles[j] + ": " + countArray[j]);
}
}
}
}
说实话,你的问题不是java的语法。我的意思是,这是java中的常识。(很抱歉,如果我因为英语不好而显得粗鲁或唐突(
请找到它。https://www.journaldev.com/12552/public-static-void-main-string-args-java-main-method我希望它能帮助你。