- P86 一维数组的使用场景 2020-03-20 01:46:46
- 编写一个程序,将用户在控制台输入的3科考试成绩保存在数组中,然后输出改用户的总成绩.
public class Dbd_TotalScore {
public static void main(String[] args) {
java.util.Scanner sc = new java.util.Scanner(System.in);
System.out.println("请输入3科成绩,用空格隔开:");
int score1 = sc.nextInt();
int score2 = sc.nextInt();
int score3 = sc.nextInt();
int score[] = { score1, score2, score3 };
System.out.println("您的成绩分别为:" + score[0] + " " + score[1] + " " + score[2]);
System.out.println("您的总成绩为" + (score1 + score2 + score3));
sc.close();
}
}
- print:
请输入3科成绩,用空格隔开:
8
9
5
您的成绩分别为:8 9 5
您的总成绩为22
============================================================================================
光盘\Code\Try\04\04
import java.util.Scanner;
public class TotalScore {
public static void main(String[] args) {
double[] score = new double[3];
double perScore = 0; // 各科成绩
double totalScore = 0; // 总成绩
Scanner sc = new Scanner(System.in);
for (int i = 0; i < score.length; i++) {
System.out.print("输入科目" + (i + 1) + "的考试成绩:");
perScore = sc.nextDouble();
score[i] = perScore;
}
for (int i = 0; i < score.length; i++) {
totalScore += score[i];
}
System.out.print("该用户的总成绩:" + totalScore);
sc.close();
}
}
-
print:
输入科目1的考试成绩:8
输入科目2的考试成绩:9
输入科目3的考试成绩:5
该用户的总成绩:22.0 -
小结:
1、数组通常的写法:int a[] = { 1, 2, 3 };(中括号放类型后面)
2、Scanner的循环提示分次录入示例:
for (int i = 0; i < score.length; i++) {
System.out.print(“输入科目” + (i + 1) + “的考试成绩:”);
perScore = sc.nextDouble();
score[i] = perScore;