您的位置:首页 > 其它

寻找最大数和第二大数

2015-10-15 15:03 267 查看


编写程序,提示用户输入学生的个数,每个学生的名字及其分数,最后显示最高分的学生和第二高分的学生。

import java.io.*;
import java.util.*;
public class Student{

public static void main( String[] args){
int n;
Scanner in = new Scanner(System.in);
System.out.println("请输入学生的个数:");
n = in.nextInt();
String[] stu=new String
;
int[] score = new int
;
for(int i=0;i<n;i++){
stu[i] = in.next();
score[i]= in.nextInt();
}
int first,second,first_i,second_i;

if(score[0]>=score[1]) {
first=score[0];
first_i=0;
second=score[1];
second_i=1;
}
else {
first=score[1];
first_i=1;
second=score[0];
second_i=0;
}

for(int i=2;i<n;i++){
if(score[i] >second){
second = score[i];
second_i = i;
if(second > first){
int t = second;
second = first;
first = t;

t = second_i;
second_i = first_i;
first_i = t;
}
}
}
System.out.println("最高分学生:" + stu[first_i]+"\t分数:"+first);
System.out.println("第二高分学生:" + stu[second_i]+"\t分数:"+second);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: