JAVA练习

编写一个程序,提示用户输入学生数量后,再依次输入姓名和成绩,按照成绩的降序来打印学生的姓 名
public class Test4 {
// 编写一个程序,提示用户输入学生数量后,再依次输入姓名和成绩,按照成绩的降序来打印学生的姓
public static void main ( String [] args ) {
System . out . println ( " 输入学生数量 " );
Scanner sc = new Scanner ( System . in );
int len = sc . nextInt ();
String [] names = new String [ len ];
int [] scores = new int [ len ];
for ( int i = 0 ; i < names . length ; i ++ ) {
names [ i ] = inputName ( sc );
scores [ i ] = inputScore ( sc );
}
sort ( names , scores );
for ( int i = 0 ; i < names . length ; i ++ ) {
System . out . println ( " " + ( i + 1 ) + " 名学生: " + names [ i ] + ", 成绩
:" + scores [ i ]);
}
}
public static String inputName ( Scanner sc ) {
System . out . println ( " 姓名: " );
String tmp = "" ;
while ( true ) {
tmp = sc . next ();
if ( tmp . length () > 20 || tmp . length () < 6 ) {
System . out . println ( " 输入数据不合法,请重新输入 " );
} else
break ;
}
return tmp ;
}
public static int inputScore ( Scanner sc ) {
System . out . println ( " 成绩: " );
int tmp = 0 ;
while ( true ) {
tmp = sc . nextInt ();
if ( tmp > 100 || tmp < 0 ) {
System . out . println ( " 输入数据不合法,请重新输入 " );
} else
break ;
}
return tmp ;
}
public static void sort ( String [] names , int [] scores ) {
for ( int i = 1 ; i < names . length ; i ++ ) {
for ( int k = 0 ; k < names . length - i ; k ++ ) {
if ( scores [ k ] < scores [ k + 1 ]) {
int tmp = scores [ k ];
scores [ k ] = scores [ k + 1 ];
scores [ k + 1 ] = tmp ;
String stmp = names [ k ];
names [ k ] = names [ k + 1 ];
names [ k + 1 ] = stmp ;
}
}
}
}
}

你可能感兴趣的:(java,开发语言)