JAVA for循环语句的循环变量类型问题
class HalfDollars { public static void main(String [] arguments) { int[] denver = {1_900_000,1_700_000,1_700_000 }; int[] philadelphia ={1_900_000,1_800_000,1_750_000}; int[] total = new int[denver.length]; int sum =0; for (int i=0,int j=2009;i<3;i++,j++) { total[i]=denver[i]+philadelphia[i]; System.out.print(j+"production:"); System.out.format("%,d%n",total[i]); sum += total[i]; } System.out.print("Average production:"); System.out.format("%,d%n",sum/3); } }
以上代码会报错:
class HalfDollars { public static void main(String [] arguments) { int[] denver = {1_900_000,1_700_000,1_700_000 }; int[] philadelphia ={1_900_000,1_800_000,1_750_000}; int[] total = new int[denver.length]; int sum =0; for (int i=0, j=2009;i<3;i++,j++) { total[i]=denver[i]+philadelphia[i]; System.out.print(j+"production:"); System.out.format("%,d%n",total[i]); sum += total[i]; } System.out.print("Average production:"); System.out.format("%,d%n",sum/3); } }
以上代码正常执行
由上可知:代码的数据类型只能是byte、char 、short、int以及String这5种;并且两个循环变量for(int x,y)的类型一定要相同,并且只能声明一次类型。