2017-10-14 68 views
0

我试图读取文件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(".", ""); 
    } 

当我编译我的代码,我得到这个错误Error:(18, 29) java: incompatible types: java.util.Scanner cannot be converted to java.lang.String

有谁知道我应该给这类型cleanWord方法请,所以它可以执行删除对单词进行操作。 谢谢

回答

1

要调用Utils.cleanWord(s2),其中s2Scanner而不是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(".", ""); 
} 

,因为你不能修改参数..尝试将导致修改参数的本地引用而不是参数本身。