- 求最大值与最小值
package com.lovo; /* *求最大值与最小值 */ public class Test01 { public static void main(String[] args) { int[] a = new int[10]; for(int i = 0; i < a.length; i++) { a[i] = (int) (Math.random() * 99 + 1); System.out.print(a[i] + "\t"); } System.out.println(); int max, min; max = min = a[0]; for(int i = 1; i < a.length; i++) { if(a[i] > max) { max = a[i]; } else if(a[i] < min) { min = a[i]; } } System.out.println("最大值: " + max); System.out.println("最小值: " + min); } }
- 摇骰子
package com.lovo; public class Test02 { public static int roll() { return (int) (Math.random() * 6 + 1); } public static void main(String[] args) { String[] strs = {"banana", "waxberry", "kiwi", "grape"}; System.out.println(strs[2]); int[] f = new int[6]; for(int i = 1; i <= 6000; ++i) { int face = roll(); f[face - 1]++; } for(int i = 0; i < f.length; i++) { System.out.println(i + 1 + "点摇出了" + f[i] + "次"); } } }
- 斐波拉切数列
package com.lovo; public class Test03 { public static void main(String[] args) { int[] f = new int[20]; f[0] = f[1] = 1; for(int i = 2; i < f.length; i++) { f[i] = f[i - 1] + f[i - 2]; } // Java 5+ for-each循环 for(int x : f) { System.out.println(x); } } }
- 成绩统计
package com.lovo; import java.util.Scanner; public class Test04 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); double[] scores = new double[6]; String[] names = {"张飞", "关羽", "马超", "黄忠", "赵云", "魏延"}; double totalScore = 0; for(int i = 0; i < scores.length; i++) { System.out.print("请输入" + names[i] + "的成绩: "); scores[i] = sc.nextDouble(); totalScore += scores[i]; } System.out.printf("平均分: %.1f\n", totalScore / scores.length); double maxScore = scores[0], minScore = scores[0]; int maxIndex = 0, minIndex = 0; for(int i = 1; i < scores.length; i++) { if(scores[i] > maxScore) { maxScore = scores[i]; maxIndex = i; } else if(scores[i] < minScore) { minScore = scores[i]; minIndex = i; } } System.out.println(names[maxIndex] + "考了最高分: " + maxScore); System.out.println(names[minIndex] + "考了最低分: " + minScore); sc.close(); } }