我在大学上课,我们正在做Java。这只是我的第四课,所以我是超级新人(很高兴)。我的问题,希望我的唯一一个是这实际上会运行但是,在要求用户输入您想要输入的学生数量之后。然后它进入for循环并同时询问接下来的两个问题然后我得到一个错误。我试图弄清楚如何让它分开问问题,但我没有运气。有人建议使用io.console,但我不认为我们可以使用它,我们还没有学到它。我遇到过hasNext,但我不确定它是如何工作的,我读的越多,它就越困惑我。
非常感谢任何帮助!
/*Write a java program that prompts the user to enter the number of students and then each student’s name and score,
* and finally displays the student with highest score and the student with the second- highest score.
* You are NOT allowed to use ‘Arrays’ for this problem (as we have not covered arrays yet).
*
* HINT: You do not need to remember all the inputs. You only need to maintain variables for max and second max
* scores and corresponding names. Whenever you read a new input, you need to compare it to the so far established
* max & second max scores and change things accordingly. */
import java.util.Scanner;
public class StudentScore {
public static void main(String[] args) {
String studentName="", highName="", secondHighName="";
int score=0, highScore=0, secondHighScore=0;
int count;
int classSize;
Scanner scan = new Scanner(System.in);
System.out.print("How many students' grades do you want to enter? ");
classSize = scan.nextInt();
for (int i = 0; i < classSize.hasNext; i++) {
System.out.print("Please enter the students name? ");
studentName = scan.hasNextLine();
System.out.print("Please enter the students score? ");
score = scan.nextInt();
}
if (score >= secondHighScore) {
secondHighScore = highScore;
secondHighName = highName;
highScore = score;
highName = studentName;
}
}
System.out.print("Student with the highest score: " + highName + " " + highScore);
System.out.print("Student with the second highest score: " + secondHighName + " " + secondHighScore);
}
}
答案 0 :(得分:1)
首先,您需要检查收到的分数是否大于第二个分数,以及该分数是否大于最高分数。其次,将studentName = scan.hasNextLine()
替换为studentName = scan.nextLine()
。同时创建一个新的Scanner
。
代码:
public static void main(String[] args) {
String studentName="", highName="", secondHighName="";
int score=0, highScore=0, secondHighScore=0;
int classSize;
Scanner scan = new Scanner(System.in);
System.out.println("How many students' grades do you want to enter? ");
classSize = scan.nextInt();
for (int i = 0; i < classSize; i++) {
System.out.println("Please enter the student #" + (i + 1) + "'s name? ");
//new Scanner plus changed to nextLine()
scan = new Scanner(System.in);
studentName = scan.nextLine();
System.out.println("Please enter the student #" + (i + 1) + " score? ");
score = scan.nextInt();
if(score >= highScore){
secondHighName = highName;
secondHighScore = highScore;
highName = studentName;
highScore = score;
} else if(score >= secondHighScore && score < highScore){
secondHighName = studentName;
secondHighScore = score;
}
}
scan.close();
System.out.println("Student with the highest score: " + highName + " " + highScore);
System.out.println("Student with the second highest score: " + secondHighName + " " + secondHighScore);
}