代碼:
package com.liron.p1; import java.io.IOException; import java.util.Scanner; /** * 求s=a+aa+aaa+aaaa+aa...a的值,其中a是一個數字。 * 例如2+22+222+2222+22222(此時共有5個數相加),幾個數相 * 加有鍵盤控制。 */ public class Topic18 { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); System.out.println("用哪個數循環?:"); int _temp = sc.nextInt(); System.out.println("循環相加多少次?:"); int temp = sc.nextInt(); int newNumber = 0; // 每次生成的新數 int total = 0; // 計算結果 for (int i = 0; i < temp; i++) { newNumber = newNumber * 10 + _temp; System.out.println(newNumber); total = total + newNumber; } System.out.println("計算結果:" + total); } }
結果: