【发布时间】:2014-07-21 23:18:54
【问题描述】:
我在大学上课,我们正在学习 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);
}
}
【问题讨论】:
-
classSize是int。classSize.hasNext可能是什么?我认为您需要回到课程所用的书并在那里找到一些代码示例。 -
hasNextLine不返回另一行,它测试是否还有另一行。所以它返回一个boolean,而不是String。另请参阅我对stackoverflow.com/questions/24871872/… 的回答,因为您即将遇到同样的问题。 -
哦,好吧,我想我现在明白了。你有没有机会给我一个简单的例子来说明 hasNextLine 是如何工作的?另外,我正在阅读你的另一篇文章,看看你在说什么其他问题。谢谢!