如何使用扫描仪确定行尾? [英] How to determine the end of a line with a Scanner?

查看:80
本文介绍了如何使用扫描仪确定行尾?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序中有一个扫描仪,可以读取文件的一部分并将其格式化为HTML。当我读取文件时,我需要知道如何使扫描仪知道它在一行的末尾并开始写入下一行。

I have a scanner in my program that reads in parts of the file and formats them for HTML. When I am reading my file, I need to know how to make the scanner know that it is at the end of a line and start writing to the next line.

这里是我代码的相关部分,让我知道是否遗漏了任何内容:

Here is the relevant part of my code, let me know if I left anything out :

//scanner object to read the input file
Scanner sc = new Scanner(file);

//filewriter object for writing to the output file
FileWriter fWrite = new FileWriter(outFile);

//Reads in the input file 1 word at a time and decides how to
////add it to the output file
while (sc.hasNext() == true)
{
    String tempString = sc.next();
    if (colorMap.containsKey(tempString) == true)
    {
        String word = tempString;
        String color = colorMap.get(word);
        String codeOut = colorize(word, color);
        fWrite.write(codeOut + " ");
    }
    else
    {
        fWrite.write(tempString + " ");
    }
}

//closes the files
reader.close();
fWrite.close();
sc.close();

我发现了 sc.nextLine(),但我仍然不知道如何确定何时到达行尾。

I found out about sc.nextLine(), but I still don't know how to determine when I am at the end of a line.

推荐答案

如果要要仅使用Scanner,您需要创建一个临时字符串,将其实例化到数据网格的nextLine()(因此它仅返回跳过的行),并创建一个新的Scanner对象来扫描该临时字符串。这样,您只使用该行,并且hasNext()不会返回误报(这并不是真正的误报,因为这是要执行的操作,但从您的情况来看,应该是这样)。您只需保持nextLine()启用第一个扫描仪并更改临时字符串,再更改第二个扫描仪以扫描每个新行,等等。

If you want to use only Scanner, you need to create a temp string instantiate it to nextLine() of the grid of data (so it returns only the line it skipped) and a new Scanner object scanning the temp string. This way you're only using that line and hasNext() won't return a false positive (It isn't really a false positive because that's what it was meant to do, but in your situation it would technically be). You just keep nextLine()ing the first scanner and changing the temp string and the second scanner to scan each new line etc.

这篇关于如何使用扫描仪确定行尾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆