使用Integer.parseInt()检查该行是否为Integer

时间:2014-02-08 15:50:03

标签: java file-io while-loop return

我正在尝试使用Integer.parsInt()方法读取文件的行号,但是在使用Integer.parsInt()和IF语句时IDE中存在错误注意:文件号是1和每行上面的2

1
00:00:01,600 --> 00:00:04,080
<b>Mr Magnussen, please state your
full name for the record.</b>

2
00:00:04,080 --> 00:00:07,040
Charles Augustus Magnussen.

我试图使用的代码给出错误,错误只是在语句

时翻转
public int lineLength() throws IOException {
    try {
        String file;
        file = "tra.srt";
        Charset charset = Charset.defaultCharset();
        Path path = Paths.get(file);
        BufferedReader reader = Files.newBufferedReader(path, charset);
        String line;
        boolean r = false;
        while ((line = reader.readLine()) != null) {
            if (Integer.parseInt(line) != r) {
                return line.length();
            }
        }
    } catch (FileNotFoundException ex) {
        System.err.println(ex);
    }

    return;

}

更改内容后,如果此代码将返回每组行的行号

     public String lineLength() throws IOException {
    try {
        String file;
        file = "tra.srt";
        Charset charset = Charset.defaultCharset();
        Path path = Paths.get(file);
        BufferedReader reader = Files.newBufferedReader(path, charset);
        String line;

        while ((line = reader.readLine()) != null) {
            if (Integer.parseInt(line) > 0) {
                return line.substring(line.length());

            }
        }
    } catch (FileNotFoundException ex) {
        System.err.println(ex);
    }

    return "";
}

1 个答案:

答案 0 :(得分:2)

在这一行:

if (Integer.parseInt(line) != r) 

您正在尝试比较intboolean,正如IDE告诉您的那样。这在Java中是不允许的。您可能希望将int与数字进行比较。