为什么有些字符串(例如topStudent1)必须设置为null,而其他字符串(例如name1)则不能,以避免编译错误?为什么有些双打(例如highScore)必须设置为0,而其他(例如score1)则不能,以避免编译错误?
public class Exercise05_09 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of students: ");
int numOfStudents = input.nextInt();
String name1;
String name2;
String topStudent1 = null;
String topStudent2 = null;
double score1;
double score2;
double highScore = 0;
double nextHighScore = 0;
int count = 2;
while (count <= numOfStudents) {
if (count == 2) {
System.out.println("Enter a student name: ");
name1 = input.next();
System.out.println("Enter a student score: ");
score1 = input.nextDouble();
System.out.println("Enter a student name: ");
name2 = input.next();
System.out.println("Enter a student score: ");
score2 = input.nextDouble();
if (score1 > score2) {
highScore = score1;
topStudent1 = name1;
nextHighScore = score2;
topStudent2 = name2;
}
else {
highScore = score2;
topStudent1 = name2;
nextHighScore = score1;
topStudent2 = name1;
}
}
else {
System.out.println("Enter a student name: ");
name1 = input.next();
System.out.println("Enter a student score: ");
score1 = input.nextDouble();
if (score1 > highScore) {
nextHighScore = highScore;
highScore = score1;
topStudent2 = topStudent1;
topStudent1 = name1;
}
else if (score1 > nextHighScore) {
nextHighScore = score1;
topStudent2 = name1;
}
}
count++;
}
System.out.printf("Top two students:\n%s's score is %3.1f\n%s's score is %3.1f\n", topStudent1, highScore, topStudent2, nextHighScore);
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢!!