Java打印文本文件的输出并检查第一个字符

问题描述 投票:0回答:1

我认为我代码的注释掉部分有效。我的问题是,当我打印出字符串“ s”时,我只会得到文本文件的最后一行。

import java.io.File; 
import java.util.Scanner; 
public class mainCode {
    public static void main(String[] args)throws Exception 
      { 
          // We need to provide file path as the parameter: 
          // double backquote is to avoid compiler interpret words 
          // like \test as \t (ie. as a escape sequence) 
          File file = new File("F:\\Java Workspaces\\Workspace\\Files\\file.txt"); 

            Scanner sc = new Scanner(file); 
            String s = new String("");

            while (sc.hasNextLine())
                s = sc.nextLine();
                System.out.println(s);
//                if (s.substring(0,1).equals("p") || s.substring(0,1).equals("a") ){
//                    System.out.println(s);
//                }
//                else{
//                    System.out.println("Error File Format Incorrect");
//                }
      }
}

输出仅是“ a192”,前面的行是“ a191”和“ a190”

java java.util.scanner string-parsing
1个回答
0
投票

您的缩进使其看起来像您的while执行了多个语句,但不是。使用花括号将要执行的语句括起来作为一个块。

        while (sc.hasNextLine())
            s = sc.nextLine();
        System.out.println(s);  // proper indentation

可能是您想要的:

  while( sc.hasNextLine() ) {
     s = sc.nextLine();
     System.out.println( s );
  }

((我必须将其放入我的IDE中才能找到它。我的IDE对我来说将第二行标记为“令人困惑的缩进”。好的IDE可以做到这一点。)

© www.soinside.com 2019 - 2024. All rights reserved.