1.Scamner 获得一组数据的最大值和平均值
public static void main(String[] args){ Scanner scanner = new Scanner(System.in); double sum = 0; int m = 0; while (scanner.hasNextDouble()){ double x = scanner.nextDouble(); sum = sum + x; m++; } System.out.println(m+"个数的和为"+sum); System.out.println(m+"个数的平均值为"+(sum/m)); scanner.close(); } 2.实现if多选择结构的持续输入(反馈成绩合格与否)
package com; import java.util.Scanner; public class Test { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (true){ int s = scanner.nextInt(); if (s>=60&s<=100){ System.out.println("成绩合格"); }else if(s>=0&s<60){ System.out.println("成绩不合格"); }else{ System.out.println("成绩不合法"); } } } } 3.Switch选择结构(匹配后输出不同结果) (记得加上break,避免case穿透现象)
package com; public class Test { public static void main(String[] args) { char grade = 'A'; switch (grade){ case 'A': System.out.println("优秀"); break; case 'B': System.out.println("良好"); break; case 'C': System.out.println("及格"); break; case 'D': System.out.println("还需努力"); break; default: System.out.println("输入错误,无法匹配"); } } }
4.While循环 (计算1+2+3+...+100=?)
package com; public class Test { public static void main(String[] args) { int i =1; int sum = 0; while (i<=100){ sum += i; i++; } System.out.println(sum); } } 注意:i++的位置,位于sum += i;上方则整体大100 5.do while循环和while循环区别之 do while至少执行一次 (多次执行结果相同) 6.For循环(分别计算0到100奇数的和与偶数的和)
package com; public class Test { public static void main(String[] args) { int oddSum = 0 ; int evenSum = 0 ; for (int i = 0; i <= 100; i++) { if (i%2==0){ evenSum += i; }else { oddSum += i; } } System.out.println(oddSum); System.out.println(evenSum); } }
7.for循环输出1-1000之间能被5整除的数,并且每行输出3个
package com; public class Test { public static void main(String[] args) { for (int i = 1; i <= 1000; i++) { if (i%5==0){ System.out.print(i+" "); if(i%15==0){ System.out.println(" "); } } } } }
8.打印九九乘法表
9.增强for循环