import java.util.Scanner;
/**
* 案例:录入某位学生的五门成绩,并计算平均分
*/
public class LoopDemo1 {
@SuppressWarnings("resource")
public static void main(String[] args) {
//科目数
Scanner sc1 = new Scanner(System.in);
//科目成绩
Scanner sc2 = new Scanner(System.in);
//科目名称
Scanner sc3 = new Scanner(System.in);
int sum = 0;//总成绩
int score = 0;//单科成绩
System.out.println("请输入你要输入成绩的科目数:");
int sub = sc1.nextInt();
if(sub==1){
System.out.println("请选择你要输入的科目名称:");
System.out.println("1.JAVA 2.C++ 3.ORACLE 4.JS");
int subN = sc3.nextInt();
String subName = null;
switch (subN) {
case 1:
subName = "JAVA";
case 2:
subName = "C++";
case 3:
subName = "ORACLE";
case 4:
subName = "JS";
}
System.out.println("你选择的科目为:"+subName);
System.out.println("请输入 "+subName+" 的成绩:");
do{
score = sc2.nextInt();
if(score<0 || score>100){
System.out.println("你输入的分数错误,请正确输入0-100之间的考试成绩数:");
}
}while(score<0 || score>100);
System.out.println("科目为 "+subName +" 的成绩为 "+score);
}else{
System.out.println("你要输入"+sub+"门成绩");
System.out.println("请分别输入你要输入的每科的分数...");
for (int i = 1; i <= sub; i++) {
System.out.println("请输入第"+i+"门成绩:");
do{
score = sc2.nextInt();
if(score<0 || score>100){
System.out.println("你输入的分数错误,请正确输入0-100之间的考试成绩数:");
}
}while(score<0 || score>100);
System.out.println("第"+i+"门成绩为"+score);
sum += score;
}
int avg = sum / sub;
System.out.println("总成绩为:"+sum+" 平均分为:"+avg);
}
}
}
本案例会出现两种情况:
一:当选择填写个数为1时,需要选择填写科目
二:当选择填选多个时,需要输入多条数据