我正在做一个家庭作业问题,并且我的循环部分存在问题
/**
* Created by wilson on 2/25/2014.
*/
import java.util.Scanner;
public class GradesDemo {
public static void main(String[] args) {
Grades grade = new Grades();
String name;
double score = 0;
boolean invalid = true;
Scanner keyboard = new Scanner(System.in);
//One loop iteration for each student
for (int i = 0; i < 5; i++) {
invalid = true;
//Asks for student name, and stores to array
System.out.println("Student's Name:");
name = keyboard.nextLine();
grade.setName(name, i);
//while loop to check if score entered by user is valid
while (invalid == true) {
System.out.println("Student's Score:");
score = keyboard.nextDouble();
//Check if score entered was valid. If not, user will be asked again
if (score >= 0 && score <= 100)
invalid = false;
else
System.out.println("Score is invalid. Must be between 0-100. Try again.");
}
grade.setScore(score, i);
//Calculate grade
grade.findGrade(i);
}
for (int i = 0; i <5; i++) {
System.out.println(grade.toString(i));
}
}
}
输出样本:
Student's Name:
John Doe
Student's Score:
88
Student's Name:
Student's Score:
正如您所看到的,在循环的第二次迭代中,它会直接跳过等待学生姓名下的用户输入到学生分数,从而导致错误。
答案 0 :(得分:1)
使用BufferReader而不是使用Scanner,它将解决所有这些问题。