如何打印第一行

时间:2015-09-08 02:56:11

标签: java

我的文字文件包括:

Mary,123,s100,59.2
Melinda,345,A100,10.1
Hong,234,S200,118.2
Ahmed,678,S100,58.5
Rohan,432,S200,115.5
Peter,654,S100,59.5

我的代码如下:

public static void main(String[] args) throws IOException {
    Scanner sc= new Scanner(new FileReader("competitors.txt"));

    while (sc.hasNext()) {
        String Str=sc.next();
        String [] s=Str.split(",");
        System.out.println(s[0]);
    }   
}

我不知道为什么它会打印第一列,我希望它打印第一行。有人可以帮忙吗?

3 个答案:

答案 0 :(得分:0)

试试这个,

public static void main(String[] args) throws IOException {
    Scanner sc= new Scanner (new FileReader("competitors.txt"));

    sc.hasNext();
    System.out.println(sc.next());
}

答案 1 :(得分:0)

如果您只想阅读第一行,那么这就是诀窍:

yytokentype

答案 2 :(得分:0)

while(sc.hasNext()) { // for every line in the file
   String Str=sc.next(); // read that line
   String [] s=Str.split(","); // split it on commas
   System.out.println(s[0]); // print the first element
}

您的代码循环遍历文件中的每一行,并在逗号上分割每一行,并将结果存储在s中。所以对于第一行s = {"Mary", "123", "s100", "59.2"}。然后它打印出s的第一个元素。对于第一行,它打印" Mary"。对于第二行s = {"Melinda", "345", ...},它打印" Melinda"。

如果您只想打印第一行,请使用:

If(sc.hasNext()) {
   String str=sc.nextLine();
   System.out.println(str);
}

正如@TAsk所提到的,你应该使用sc.nextLine()代替sc.next(),因为后者将读取直到空格,而前者将读取直到行尾。

相关问题