使用扫描仪和跳过行读取文件时出现问题

时间:2015-11-18 16:37:36

标签: java

我需要在java中用Scanner读取以下txt.file。这个文件的问题是我不需要很多信息。我需要的唯一的东西是参数和那些参数的值(作为一个例子,我需要String n和int 5,String p和double 0.5,String lambda和double 0.3 ......)问题似乎是在空行。我添加了我制作的代码,但如果我运行它,则永远不会读取分发的第二行。

我做错了什么?

txt-file作为输入:

distributie lengte klasse 1 naam verdeling  parameter(s)    value of parameter
                        n       5
                        p       0.5
distributie lengte klasse 2 naam verdeling  parameter(s)    value of parameter
                        lambda      0.3

distributie incidentie klasse 1 naam verdeling  parameter(s)    value of parameter
                        d       1

distributie incidentie klasse 2 naam verdeling  parameter(s)    value of parameter
                        n       8
                        p       0.1     
distributie servertijd klasse 1 naam verdeling  parameter(s)    value of parameter
                        d       1

distributie servertijd klasse 2 naam verdeling  parameter(s)    value of parameter
                        p       0.3

aantal pakketten te verwerken                   2000000

代码

for(int a = 0; a< 6; ++a){

 inputStream.nextLine();
 System.out.print("\n"+inputStream.next());
 System.out.print("\n"+inputStream.next());
 String line = "";
 if (!(line = inputStream.nextLine()).isEmpty()) 
    {
     System.out.print("\n"+inputStream.next());
     System.out.print("\n"+inputStream.next());
    }
 else
 {

 }
 inputStream.nextLine();
 }}

2 个答案:

答案 0 :(得分:0)

以下是一些改进:

  • 对于循环标题,我使用a++来增加a - 只是偏好。
  • .nextLine()返回String,因此可能会在执行inputStream后重置.nextLine()变量。
  • 打印inputStream.nextLine()而不是inputStream.next()
  • if条件中,我不会初始化变量line
  • if else条件并不需要在那里做你想做的事情,即阅读六个值。

我的建议是阅读REGEX,如果该行的REGEXn,p,lamda,d匹配,则打印另一个值,然后打印。

for(int a = 0; a< 6; a++){
    inputStream.nextLine();
    //possibly reset inputStream here with something like inputStream = new Scanner(...);
    System.out.print("\n"+inputStream.nextLine());
    System.out.print("\n"+inputStream.nextLine());
}

答案 1 :(得分:0)

简短回答:不要使用Scanner

你说你想用扫描仪方法&#34;来阅读下面的txt.file,但是你没有说出原因,我们也不总是得到我们喜欢的东西。在这种情况下,使用Scanner远非最佳选择。

查看文件,格式似乎是3行数据块,第一行以单词distributie开头。在文件末尾有一个以aantal开头的摘要行。

每个块的第2行和第3行是关键字+十进制数或空行。由于您只是在那些关键字+数字对之后,我建议逐行阅读文件,并使用正则表达式匹配关键字+数字行:

try (BufferedReader in = new BufferedReader(new FileReader(file))) {
    Pattern p = Pattern.compile("\\s+(\\w+)\\s+([0-9.]+)\\s*");
    for (String line; (line = in.readLine()) != null; ) {
        Matcher m = p.matcher(line);
        if (m.matches()) {
            String keyword = m.group(1);
            double number = Double.parseDouble(m.group(2));
            System.out.println(keyword + " = " + number);
        }
    }
}