Skip to content

Instantly share code, notes, and snippets.

@fanker
Created September 26, 2012 05:29
Show Gist options
  • Save fanker/3786281 to your computer and use it in GitHub Desktop.
Save fanker/3786281 to your computer and use it in GitHub Desktop.
利用数组循环输入学生成绩,并排序输出
public class PaiXu {
public static void main (String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
int [] nums = new int [5]; //定义数组,开辟空间
/*int [] nums;
nums = new int [5]; //另外的一种定义数组的方法
*/
System.out.println("数组长度为" + nums.length); //输出数组的长度
for (int i =0; i < nums.length; i++) {
System.out.println("请输入第" + (i + 1) + "位同学的成绩:");
nums [i] = input.nextInt(); //利用数组循环输入学生成绩
}
System.out.println("------------------------------"); //分割线
System.out.println("成绩高低排序为:");
for (int i = 0; i < nums.length - 1; i++) {
for (int j = 0; j < nums.length - i - 1; j++) { //对输入数据进行从高到低的排序
if (nums [j] < nums [j + 1]) {
int temp = nums [j]; //引入一个临时变量temp
nums [j] = nums [j + 1];
nums [j + 1] = temp;
}
}
}
/*for (int i = 0; i < nums.length - 1; i++) {
for (int j = 0; j < nums.length - i - 1; j++) { //对输入数据进行从低到高的排序
if (nums [j] > nums [j + 1]) {
int temp = nums [j]; //引入一个临时变量temp
nums [j] = nums [j + 1];
nums [j + 1] = temp;
}
}
}
*/
for (int num : nums) {
System.out.println(num); //对排序结果进行输出
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment