1.数组遍历-求和
需求:某部门4名员工的销售额分别是:67、45、34、99,请计算出他们部门的总销售额。
public static void main(String[] args) {
//静态初始化数组
int[] money = {67, 45,34,99};
int sumMoney = 0;
for (int i = 0; i < money.length; i++) {
sumMoney += money[i];
}
System.out.println("他们部门的总销售额:" + sumMoney);
}
}
2.评委打分案例
需求:可以录入5名评委的打分,录入完毕后立即输出平均分做为选手得分。
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//定义一个数组装入所有的评委的打分
double[] scores = new double[5];
double sumScore = 0;
double ageScore = 0;
for (int i = 0; i < scores.length; i++) {
System.out.println("请输入第" + (i + 1) + "个评委的打分:");
double score = sc.nextDouble();
scores[i] = score;
sumScore += scores[i];
}
ageScore = sumScore / scores.length;
System.out.println("总分:" + sumScore);
System.out.println("平均分:" + ageScore);
}
3.成绩数据分析
需求:某班级学生的考试成绩是:99, 100, 62, 15, 48, 65, 98, 99, 5, 59.5, 75。
请统计及格学生总人数。
public static void main(String[] args) {
double[] scores = {99, 100, 62, 15, 48, 65, 98, 99, 5, 59.5, 75};
//用于计数
int count = 0;
for (int i = 0; i < scores.length; i++) {
if (scores[i] >= 60){
count++;
}
}
System.out.println("及格学生总人数:" + count);
}
4.数组元素求最大值
需求:15, 9000, 56, 89, 200, -5 中输出最大值
public static void main(String[] args) {
int[] num = {15, 9000, 56, 89, 200, -5};
int max = num[0];
for (int i = 0; i < num.length; i++) {
if (max < num[i]){
max = num[i];
}
}
System.out.println("最大值:" + max);
}
5.数组反转
需求 某个数组有5个数据:10,20,30,40,50。请将这个数组中的数据进行反转。
[10, 20, 30, 40, 50] 反转后 [50, 40, 30, 20, 10]
public static void main(String[] args) {
int[] num = {10, 20, 30, 40, 50};
for (int i = 0, j = num.length - 1; i < j; i++, j--) {
int temp = num[j];
num[j] = num[i];
num[i] = temp;
}
for (int i = 0; i < num.length; i++) {
System.out.print(num[i] + " ");
}
}