2018/12/04 PAT刷题 L1-008 求整数段和 java
使用Scanner的方法, 代码如下:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int a, b; a = scanner.nextInt(); b = scanner.nextInt(); int[] list = new int[b - a + 1]; int cnt = 0; int sum = 0; for (int i = a; i <= b; i++) { if (cnt < 5) { System.out.printf("%5d", i); cnt++; sum += i; } else { System.out.println(); System.out.printf("%5d", i); sum += i; cnt = 1; } } System.out.println(); System.out.print("Sum = " + sum); } }
使用更加高效的BufferedReader, 代码如下:
import java.io.BufferedReader; import java.io.InputStreamReader; public class Main2 { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int a, b; String[] str = br.readLine().split(" "); a = Integer.parseInt(str[0]); b = Integer.parseInt(str[1]); // int[] list = new int[b - a + 1]; int cnt = 0; int sum = 0; for (int i = a; i <= b; i++) { if (cnt < 5) { System.out.printf("%5d", i); cnt++; sum += i; } else { System.out.println(); System.out.printf("%5d", i); sum += i; cnt = 1; } } System.out.println(); System.out.print("Sum = " + sum); } }