java獲取整數各個位上的數


 感覺搜這個的比較多,把這個完善一下。希望對你們有幫助。

我博客的其他東西也還行的哈,可以看看。

java獲取整數各個位上的數

思想是:先取余,然后除以10,得到temp,再取余,再除以10 ,得到temp,依次類推

 

下面是我寫項目的一部分,寫了循環結構獲取每一位的數字,把代碼貼出來了,

這個函數的作用是獲取每一位數字,然后依次畫到屏幕上。

 

public void drawValue(Graphics g){
//        System.out.println(value);
        int power = value;
        if(power > 99999){
            power = 99999;
        }
        int[] arr = new int[5];
        for (int i = 0; i < 5; i++) {
            arr[i] = power % 10 ;
            power /= 10;
//            System.out.println(arr[i]);
        }
        /*
        * 依次畫出每一位的部分
        * */
        int temp = 0; // 用於計算是否是高位為零
        for (int i = 4; i >= 0; i--) {
            if (arr[i] != 0 || (temp > 0)){
//                System.out.println(arr[i]);
                g.drawImage(imgs[ arr[i] ],x - i * 25,y,null);
                temp++;
//                System.out.println(arr[i]);
            }
        }
    }

 

未用循環結構:

 

import java.util.Scanner; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc =new Scanner(System.in); int num=sc.nextInt(); int f[]=new int[10]; //我寫的是四位數,可以思考下寫成循環的形式,思想都是一樣的  int temp = num;
        f[0] = temp % 10;
        temp = temp / 10;
        f[1] = temp % 10;
        temp /= 10;
        f[2] = temp % 10;
        temp /= 10;
        f[3] = temp % 10;
System.out.print(f[3]+" "+f[2]+" "+f[1]+" "+f[0]); } }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM