gpt4 book ai didi

java - 方法的表达式开头非法

转载 作者:行者123 更新时间:2023-12-01 22:09:58 24 4
gpt4 key购买 nike

下面是一些代码,尝试查找超过一定数量字符的第一个单词。

public class FirstMatch {
public static void main(String[] args) throws java.io.FileNotFoundException {
Scanner in = new Scanner(new FileReader("aliceInWonderland.txt"));
String longWord = "";
boolean found = false;

public void threshold (int Threshold) {
while (in.hasNext() && !found) {
String word = in.next();
if (word.length() > Threshold) {
longWord = word;
found = true;
}
}
System.out.println("The first long word is: " + longWord);
}
}
}

(在上面的代码中我没有复制所有的导入语句)由于某种原因,我的阈值方法它返回非法的表达式开始。我认为这是一个愚蠢的错误,但无法弄清楚出了什么问题......

最佳答案

您应该在 main 方法之外声明您的 threshold 方法。

方法只能在类级别创建,而不能在另一个方法内创建。

import java.io.FileReader;
import java.util.Scanner;

public class FirstMatch {

public static void main(String[] args) throws java.io.FileNotFoundException {
Scanner in = new Scanner(new FileReader("aliceInWonderland.txt"));
threshold(in, 10);
}

public static void threshold(Scanner in, int threshold) {
String longWord = "";
boolean found = false;
while (in.hasNext() && !found) {
String word = in.next();
if (word.length() > threshold) {
longWord = word;
found = true;
}
}
System.out.println("The first long word is: " + longWord);
}

}

关于java - 方法的表达式开头非法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32011743/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com