首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Java 入門實戰:輸入數字輸出對應數量的星號

     編輯:程式設計疑難解答

需求分析

從控制台讀取一個正整數 n,在控制台打印 n 個 * 字符。這是 Java 基礎語法練習的經典入門題,涉及輸入流、循環控制、字符串拼接等核心知識點。

三種實現方式

方法一:for 循環逐個打印(最直觀)

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();  // 換行
    }
}

方法二:String.repeat()(Java 11+,最簡潔)

public class StarPrinter {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        System.out.println("*".repeat(n));  // 一行搞定
    }
}

方法三:StringBuilder 拼接(高性能,適合大數據量)

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() 的性能差異。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved