【问题标题】:Reading File by line instead of word by word逐行而不是逐字读取文件
【发布时间】:2013-12-17 14:30:55
【问题描述】:

我正在尝试编写一些代码来扫描输入文件中的回文,但它从每个单词而不是每一行获取字符串。例如,racecar 会显示为 racecar= palindrome 或 too hot to hoot = palindrome,但它会变得 too= not a palindrome、hot= not a palindrome 等。

这是我目前正在做的读取文件

File inputFile = new File( "c:/temp/palindromes.txt" );
Scanner inputScanner = new Scanner( inputFile );
while (inputScanner.hasNext())
{
    dirtyString = inputScanner.next();

    String cleanString = dirtyString.replaceAll("[^a-zA-Z]+", "");

    int length  = cleanString.length();
    int i, begin, end, middle;

    begin  = 0;
    end    = length - 1;
    middle = (begin + end)/2;

    for (i = begin; i <= middle; i++) {
        if (cleanString.charAt(begin) == cleanString.charAt(end)) {
            begin++;
            end--;
        }
        else {
            break;
        }
    }
}

【问题讨论】:

  • 你读过Scanner api吗?或许这种方法可以解决Scanner#nextLine()
  • 读取文件?我肯定会使用BufferedReader
  • 您应该始终格式化您的代码。我对其进行了编辑,由于代码不完整,我不得不假设您打算添加两个}。如果你格式化你的代码,你将能够发现这样的错误。

标签: java file input line


【解决方案1】:

您需要进行以下更改

改变

while (inputScanner.hasNext()) // This will check the next token.

and 

dirtyString  = inputScanner.next(); // This will read the next token value.

while (inputScanner.hasNextLine()) // This will check the next line.

and dirtyString = inputScanner.nextLine(); // This will read the next line value.

inputScanner.next() 将读取下一个令牌

inputScanner.nextLine() 将读取一行。

【讨论】:

    【解决方案2】:

    要从文件中读取一行,你应该使用 nextLine() 方法而不是 next() 方法。

    两者的区别是

    nextLine() - 将此扫描器前进到当前行并返回被跳过的输入。

    虽然

    next() - 从此扫描器中查找并返回下一个完整令牌。

    因此,您必须更改 while 语句以包含 nextLine(),使其看起来像这样。

    while (inputScanner.hasNextLine()) and dirtyString = inputScanner.nextLine();
    

    【讨论】:

      【解决方案3】:
      FileReader f = new FileReader(file);
      BufferedReader bufferReader = new BufferedReader(f);
      String line;
      //Read file line by line and print on the console
      while ((line = bufferReader.readLine()) != null)   {
              System.out.println(line);
      }
      

      以上代码段逐行从文件中读取输入,如果不清楚,please see this for complete program code

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多