/ * *(排序学生)编写一个程序,提示用户输入学生人数, *学生的姓名,他们的分数,并打印学生姓名减少 *他们的分数顺序。 * /
package homework6_17;
import java.util.Scanner;
public class Homework6_17 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter number of students: ");
int numberOfStudents = input.nextInt();
String[] names = new String[numberOfStudents];
for (int i = 0; i < numberOfStudents; i++) {
System.out.println("Enter the name of student: ");
names[i] = input.nextLine();
}
double[] scores = new double[numberOfStudents];
for (int i = 0; i < numberOfStudents; i++) {
System.out.println("Enter the score of student: ");
scores[i] = input.nextDouble();
}
String temps = "";
double temp = 0;
double max = scores[0];
for(int i = 0; i<(scores.length-1); i++){
if(scores[i+1]>scores[i]){
temp=scores[i+1];
scores[i]=scores[i+1];
scores[i+1]=scores[i];
temps = names[i+1];
names[i]=names[i+1];
names[i+1]=names[i];
}
}
for(int i = 0 ; i<(scores.length-1); i++)
System.out.println(names[i]+ " " + scores[i]);
}
}
当我运行这个程序时; 运行:
输入学生人数:3
输入学生姓名: 输入学生姓名: 一个
输入学生姓名: B'/ P>
输入学生的分数: ç
Exception in thread "main" java.util.InputMismatchException
//我输入了“输入学生姓名:”两次而不是一次。
答案 0 :(得分:0)
当您在System.out.print("Enter number of students: ");
循环中为每个学生打印短语时,您只需删除第一个for
。因此,您要为第一个学生打印两次(循环前一次,循环中一次)
答案 1 :(得分:0)
首先想到的是(不确定这里是否正确)是您输入学生人数并按“输入”。它读取第一个int(3)并读取“enter”作为第一个学生的第一个输入。
也许试试int numberOfStudents = Integer.ParseInt(input.nextLine());
?
这样,换行符就不会添加到学生中。
答案 2 :(得分:0)
在SO中回答作业问题不是一个好主意。但是既然你已经尝试了一些代码,那么回答问题就可以了。看看:
import java.util.Scanner;
public class Homework6_17 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter number of students: ");
int numberOfStudents = input.nextInt();
String[] names = new String[numberOfStudents];
for (int i = 0; i < numberOfStudents; i++) {
System.out.println("Enter the name of student #" + (i + 1) + ":");
names[i] = input.next();
}
double[] scores = new double[numberOfStudents];
for (int i = 0; i < numberOfStudents; i++) {
System.out.println("Enter the score of student " + names[i] + ":");
scores[i] = input.nextDouble();
}
String tempName;
double tempScore;
for (int i = 0; i < numberOfStudents; i++) {
for (int k = i + 1; k < numberOfStudents; k++) {
if (scores[k] > scores[i]) {
tempName = names[i];
tempScore = scores[i];
names[i] = names[k];
scores[i] = scores[k];
names[k] = tempName;
scores[k] = tempScore;
}
}
}
for (int i = 0; i < numberOfStudents; i++)
System.out.println(names[i] + " " + scores[i]);
}
}