1. 程式人生 > >分解一個使用者輸入的整數,並將各位數和各位數的和打印出來

分解一個使用者輸入的整數,並將各位數和各位數的和打印出來

例如給一個0-10000的整數6789;分解出6/7/8/9並計算6+7+8+9=24;
下列程式碼:

package com.test;
import java.util.Scanner;
import org.junit.Test;
public class Dame {
	@Test
	public void run1() {
		Scanner scan = new Scanner(System.in);
		System.out.println("請輸入四位數的數字!");
		// 此行程式碼會阻塞,等待使用者從鍵盤輸入int型別資料,並接受資料賦值給變數i。
		int i = scan.nextInt();
        if(999<i&&i<9999) {
		int x1 = i / 1000;
		int x2 = i / 100 % 10;
		int x3 = i / 10 % 10;
		int x4 = i % 10;
		System.out.println("各位數字之和為"+(x1 + x2 + x3 + x4));
		System.out.println("x1="+x1);
		System.out.println("x2="+x2);
		System.out.println("x3="+x3);
		System.out.println("x4="+x4);
        }else {
			System.out.println("您輸入的數字格式有誤;");
			run1();
		};
        
	}
}

執行結果:
在這裡插入圖片描述