首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >逐行读取文件而不是逐字读取文件

逐行读取文件而不是逐字读取文件
EN

Stack Overflow用户
提问于 2013-12-02 08:06:24
回答 3查看 1.2K关注 0票数 4

我正在尝试编写一些代码来扫描输入文件中的回文,但它从每个单词而不是每行获取字符串。举个例子,赛车会显示为racecar=回文,或者太热,不能回文,但它不会回文,hot=不会回文,等等。

下面是我目前正在执行的读取文件的操作

代码语言:javascript
复制
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;
        }
    }
}
EN

回答 3

Stack Overflow用户

发布于 2013-12-02 08:10:00

您需要进行以下更改

变化

代码语言:javascript
复制
while (inputScanner.hasNext()) // This will check the next token.

and 

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

代码语言:javascript
复制
while (inputScanner.hasNextLine()) // This will check the next line.

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

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

inputScanner.nextLine()将读取一行。

票数 3
EN

Stack Overflow用户

发布于 2013-12-02 08:16:24

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

两者之间的区别是

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

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

因此,您必须更改while语句,使其包含nextLine(),使其如下所示。

代码语言:javascript
复制
while (inputScanner.hasNextLine()) and dirtyString = inputScanner.nextLine();
票数 1
EN

Stack Overflow用户

发布于 2014-06-16 00:53:09

代码语言:javascript
复制
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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20318872

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档