我看到增強型for很方便,試着能不能用增強型for語句把鍵盤輸入的數字賦值到數組的各個元素中去。
//使用增強for 循環的將用戶輸入的數字賦到數組中去
package Lianxi; import java.util.*; public class Lianxi46 { public static void main(String[] args) { Scanner input =new Scanner(System.in); int suZu[]=new int[5]; //定義長度為5的數組 for(int i:suZu){ //使用增強型for循環 System.out.println("請輸入數字:"); suZu[i]=input.nextInt(); //循環的將鍵盤輸入的值賦到數組的各個元素中 } System.out.println(suZu[2]); //輸出數組中第三個元素 } }
結果為0!
增強型for只能用於出去數組中的元素,並賦值給變量之中。
由於之前定義數組時,沒給元素賦值,所有元素默認為0 所以此方法不成立。