Java基本語法

Young_618發表於2018-05-30

迴圈

判斷一個數(小於10位)的位數。輸入999,則輸出“它是個3位的數!”

//S1
public class HelloWorld{
    public static void main(String[] args){
        int num = 999;
        int count = 0;
        for (int i = 1; num / i != 0; i *= 10) {
            count++;
        }
        System.out.println("它是個" + count + "位的數!");
    }
}

//S2
public class HelloWorld{
    public static void main(String[] args){
        int num = 99;
        int count = 0;
        while(num>=10) {
            count+=1;
            num=num/10;
        }
        count=count+1;
        System.out.println("它是個"+count+"位的數!");
    }   
}  

陣列

package com.imooc;
//一維陣列
public class HelloWorld{
    public static void main(String[] args) {
        int[] stu=new int[5];
        stu[0]=33;
        System.out.println(stu[0]);

        int[] stud= {1,2,3,4,5};   //整體賦值
        System.out.println(stud[0]);

        int stuu[];   //宣告
        stuu=new int[5];   //分配空間
        System.out.println(stuu[0]);

        int stut[]=new int[]{111,121,222};
        System.out.println(stut[0]);
    }
}

//二維陣列
public class HelloWorld{
    public static void main(String[] args) {
        int[][] two=new int[2][4];
        System.out.println(two[1][3]);

        int[][] test= {{3,2,4},{5,3,6}};
        System.out.println(test[0][1]);

        int[][] numb=new int[3][];
        numb[0]=new int[2];
        numb[1]=new int[4];
        numb[2]=new int[2];
    }
}