Java 打印文本文件的输出并检查第一个字符
Java printing output of text file and checking first character
我认为我的代码中注释掉的部分有效。我的问题是当我打印出字符串 "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"
您的缩进看起来像是您的 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 将第二行标记为 "Confusing Indentation" 对我来说。好的 IDE 这样做.)
我认为我的代码中注释掉的部分有效。我的问题是当我打印出字符串 "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"
您的缩进看起来像是您的 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 将第二行标记为 "Confusing Indentation" 对我来说。好的 IDE 这样做.)