案例1
从键盘读入学生成绩,找出最高分,并输出学生成绩等级
- 成绩>=最高分-10 等级为’A’
- 成绩>=最高分-20 等级为’B’
- 成绩>=最高分-30 等级为’C’
- 其余 等级为’D’
提示:先读入学生人数,根据人数创建int数组,存放学生成绩。
public static void ScoreTest() { //提示输入学生人数 System.out.println("请输入学生人数:"); Scanner scanner = new Scanner(System.in); int cnt = scanner.nextInt(); //根据输入人数定义数组 int[] score = new int[cnt]; //循环输入成绩 int maxScore = 0; System.out.println("请输入 " + cnt + " 个学生成绩 "); for (int i = 0; i < score.length; i++) { score[i] = scanner.nextInt(); //最大值 if (maxScore < score[i]) { maxScore = score[i]; } } //最大值 System.out.println("最高分是 " + maxScore); //遍历数组,取出分级信息 char grade; for (int i = 0; i < score.length; i++) { if (score[i] >= maxScore - 10) { grade = 'A'; } else if (score[i] >= maxScore - 20) { grade = 'B'; } else if (score[i] >= maxScore - 30) { grade = 'C'; } else { grade = 'D'; } System.out.println("student " + i + " socre is " + score[i] + ", grade is " + grade); } //关闭资源 scanner.close(); }
运行效果
请输入学生人数: 5 请输入 5 个学生成绩 88 99 66 55 32 最高分是 99 student 0 socre is 88, grade is B student 1 socre is 99, grade is A student 2 socre is 66, grade is D student 3 socre is 55, grade is D student 4 socre is 32, grade is D
案例2
输出英文星期几
用一个数组,保存星期一到星期天的7个英语单词,从键盘输入1-7,显示对应的单词 {"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"}
public static void WeekArrayTest() { //1. 声明并初始化星期的数组 String[] weeks = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}; //2. 使用Scanner从键盘获取1-7范围的整数 Scanner scanner = new Scanner(System.in); System.out.println("请输入[1-7]范围的整数:"); int number = scanner.nextInt(); if (number < 1 || number > 7) { System.out.println("你输入的输入非法"); } else { //3. 根据输入的整数,到数组中相应的索引位置获取指定的元素(即:星期几) System.out.println("对应的星期为:" + weeks[number - 1]); } scanner.close(); }
运行效果
请输入[1-7]范围的整数: 5 对应的星期为:Friday标签:一维,grade,System,int,score,举例,数组,println,输入 From: https://www.cnblogs.com/wdh01/p/17207034.html