輸入多行,每行兩個整數(空格分隔),輸出每行兩數之和,每行一個結果。
import java.util.Scanner;
public class SumPairs {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNextLine()) { // 按行讀取,直到EOF
String line = sc.nextLine().trim();
if (line.isEmpty()) continue; // 跳過空行
String[] parts = line.split("\\s+"); // 正則匹配多個空格
if (parts.length < 2) continue; // 格式校驗
try {
int a = Integer.parseInt(parts[0]);
int b = Integer.parseInt(parts[1]);
System.out.println(a + b);
} catch (NumberFormatException e) {
System.err.println("非整數輸入: " + line);
}
}
sc.close();
}
}
sc.hasNextLine()配合nextLine()逐行處理,適用重定向文件輸入java SumPairs < data.txt。split("\\s+")兼容任意數量空格/制表符分隔。// BufferedReader + StringTokenizer 更快
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line);
if (st.countTokens() >= 2) {
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
System.out.println(a + b);
}
}
System.out.print("請輸入..."),直接讀取標準輸入。Main,包名為默認包。