我正在尝试读取文件test.txt
,一一获取所有单词,然后从读取的单词中删除点和逗号。
这是我的代码:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Utils {
public static void readFile(){
Scanner word = null;
try {
word = new Scanner(new File("test.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (word.hasNextLine()) {
Scanner s2 = new Scanner(word.nextLine());
Utils.cleanWord(s2);
while (s2.hasNext()) {
String s = s2.next();
System.out.println(s);
}
}
}
private static void cleanWord(String word){
word = word.replace(".", "");
}
当我编译代码时,出现此错误错误:(18, 29) java: 不兼容的类型:java.util.Scanner 无法转换为 java.lang.String
有谁知道我应该为 cleanWord
方法指定哪种类型,以便它可以对单词执行删除操作。
谢谢
最佳答案
您正在调用 Utils.cleanWord(s2)
,其中 s2
是 Scanner
而不是 String
。
您的代码应该是:
while(s2.hasNext()) {
String s = s2.next(); //or s2.nextLine(); depending on what you want..
s = Utils.cleanWord(s);
System.out.println(s);
}
此外,Java 参数是引用,而不是指针。您不能分配给单词参数并期望它在函数外部更改..
private static void cleanWord(String word){
word = word.replace(".", "");
}
实际上应该是:
private static String cleanWord(String word){
return word.replace(".", "");
}
因为您无法修改参数。尝试这样做将导致修改参数的本地引用,而不是参数本身。
关于java - 删除字符串中的句号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46750056/