標籤:
1.計算天數
/*給定一個年月日,計算是一年的第幾天(如輸入:2 15 結果:第46天)*/public class Demo1 {public static void main(String[] args){int year = 2012;int month = 12;int day = 31;int total = 0;//累計天數/*switch(month - 1) {//0 - 11case 0: total = day;break;case 1: total = 31 + day;break;case 2: total = 31 + 28 + day;break;case 3: total = 31 + 28 + 31 + day;break;}switch(month - 1) {//0 - 11case 11: total += 30;case 10: total += 31;case 9: total += 30;case 8: total += 31;case 7: total += 31;case 6: total += 30;case 5: total += 31;case 4: total += 30;case 3: total += 31;case 2: total += 28;case 1: total += 31;case 0: total += day;}*///數組int[] a = {0,31,28,31,30,31,30,31,31,30,31,30,31};for(int i = 0; i < month; i++ ){ total += a[i];}total += day;//判斷閏年if(year % 400 == 0 || year % 4 == 0 && year % 100 != 0){if(month > 2) total++;}System.out.println("total = " + total);}}
2.猴子吃桃
/*猴子吃桃問題。猴子第一天摘下若干個桃子,當即吃了一半,還不過癮,又多吃了一個。第二天早上又將剩下的桃子吃掉了一半,又多吃了一個。以後每天早上都吃了前一天剩下的一半零一個。到第10天早上想再吃時,就只剩一個桃子了。求第一天共摘多少桃子長度為10的int數組,放入10個隨機數,輸出最大、最小數*/public class Demo2 {public static void main(String[] args){/*int total = 1; // 10 - 2 10 - 1for(int i = 10 ; i > 1; i-- ){ total = (total + 1) * 2;//前一天的桃子數}System.out.println("total = " + total);*/int[] a = {5,2,4,6,9,0,3,11,7,8};int max, min;max = a[0]; min = a[0];for(int i = 1; i < a.length; i++) { if(max < a[i]) { max = a[i];System.out.println("max ===> " + max);}if(min > a[i]){min = a[i];}}System.out.println("max = " + max);System.out.println("min = " + min);}}
3.列印
/*6 1 2 3 4 55 6 1 2 3 44 5 6 1 2 33 4 5 6 1 22 3 4 5 6 11 2 3 4 5 6*/public class Demo3 {public static void main(String[] args){int[] a = {1,2,3,4,5,6};int k = 5;for(int i = 0; i < a.length; i++) { for(int j = 0; j < a.length; j++) { System.out.print(a[k] + " "); k++; if( k == 6) { k = 0; } } System.out.println(); k--;//a數組的索引退一個位置}}}
java新手筆記6