題目描述
EOF(End Of File)是一個條件,表示電腦作業系統已經讀取到資料來源的結尾,沒有東西可以再讀取了。這個題目將會讀取n行資料,直到達到EOF的時候,將所有讀到的n行資料標上行號並輸出。
提示:Java的Scanner物件有個「hasNext」方法可以協助解決這個問題。
原題網址
輸入格式
從基本輸入串流中讀取未知確切行數的n行資料,直到到達EOF。每行資料,都包含著非空字串。
輸出格式
將每行輸入的字串前加上行號和一個空格字元來輸出。
範例輸入
Hello world
I am a file
Read me until end-of-file.
I am a file
Read me until end-of-file.
範例輸出
1 Hello world
2 I am a file
3 Read me until end-of-file.
2 I am a file
3 Read me until end-of-file.
解題概念
使用Scanner物件的「hasNext」方法,判斷是否已經讀取到EOF。如果還沒,就讀取一整行,並格式化輸出;如果已經到達EOF,就不再讀取。
參考答案
import java.util.Scanner;
public class Solution {
public static void main(final String[] args) {
final Scanner sc = new Scanner(System.in);
int line = 0;
while (sc.hasNext()) {
final String s = sc.nextLine();
++line;
System.out.printf("%d %s%n", line, s);
}
}
}