從控制台讀取一個正整數 n,在控制台打印 n 個 * 字符。這是 Java 基礎語法練習的經典入門題,涉及輸入流、循環控制、字符串拼接等核心知識點。
import java.util.Scanner;
public class StarPrinter {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("請輸入一個正整數:");
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
System.out.print("*");
}
System.out.println(); // 換行
}
}
public class StarPrinter {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.println("*".repeat(n)); // 一行搞定
}
}
public class StarPrinter {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
StringBuilder sb = new StringBuilder(n);
for (int i = 0; i < n; i++) sb.append('*');
System.out.println(sb.toString());
}
}
實際開發中必須考慮非法輸入:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("請輸入正整數:");
if (!sc.hasNextInt()) {
System.err.println("錯誤:輸入必須為整數!");
return;
}
int n = sc.nextInt();
if (n <= 0) {
System.err.println("錯誤:數字必須大於 0!");
return;
}
// n 過大時防止 OOM
if (n > 1_000_000) {
System.err.println("數字過大,已限制為 1,000,000");
n = 1_000_000;
}
System.out.println("*".repeat(n));
}
| 錯誤現象 | 原因 | 修正 |
|---|---|---|
| 輸出為數字而非星號 | 誤寫 System.out.print(i) | 改為 System.out.print("*") |
| 只輸出一個星號 | 循環條件寫錯 i <= n 或缺少循環 | 檢查循環邊界 i < n |
| 無法編譯 | 缺少 import java.util.Scanner; | 補全導入語句 |
掌握 Scanner 輸入、for 循環控制、字符串拼接三種方式,並養成「先校驗再業務」的防禦性編程習慣,即可輕鬆應對此類入門題目。建議初學者多動手敲代碼,體會 StringBuilder 與 repeat() 的性能差異。