JAVAutil。扫描器Java扫描器跳过迭代
我已经在一个问题上陷入了一段时间,而这个程序并没有做我认为它应该做的事情
当我运行程序时,它会询问您课程名称,程序会跳过第一次迭代,或者根据输入的课程数量跳过其他迭代。它只允许在最后一次迭代中输入。对于下面的For循环,程序跳过它们而不允许输入
我的问题是,for循环是否不正确,或者字符串数组是否没有正确地将信息输入到它们的下标强>
import java.util.Scanner; //Needed for Scanner class
public class StudentRecords
{
public static void main(String[] args)
{
int courses;
int students;
int[] course = new int[5];
int[] student = new int[5];
double GPA = 0;
String[] courseNumber = new String[5];
double[] creditHours = new double[5];
String[] letterGrade = new String[5];
//Scanner object for user input
Scanner kb = new Scanner(System.in);
System.out.println("This program will help you determine the GPA \n"
+ "for each student entered.");
System.out.println("");
System.out.println("How many student's GPA are you going to calculate?");
System.out.print("Enter amount of students (Maximum of 5 students): ");
students = kb.nextInt();
student = new int[students];
System.out.println("");
for(int index = 0 ; index < student.length; index++)
{
System.out.print("Student " + (index + 1) + " information: ");
System.out.println("");
System.out.print("How many courses did student " +
(index + 1) + " take? ");
courses = kb.nextInt();
course = new int[courses];
for(int i = 0; i < course.length; i++)
{
System.out.println("What is the name of course #" + (i + 1));
courseNumber[i] = kb.nextLine();
}
for(int i = 0; i < course.length; i++)
{
System.out.println("How many credit hours is " + courseNumber[i]);
creditHours[i] = kb.nextDouble();
}
for(int i = 0; i < course.length; i++)
{
System.out.println("What is the final letter grade for " + courseNumber[i]);
letterGrade[i] = kb.nextLine();
}
for( i = 0; i < student.lenght<
}
}
}
另外,这是我正在研究的问题:
Write a program with the following inputs, all of which are stored in arrays (size 5). First how many courses the student took that semester (can’t be greater than 5). Store in ARRAYS for each student, the course number/name (for example ICT 435), credit hour ( 1-4), and letter grade(A-F). Determine the GPA for the semester.
# 1 楼答案
{}{}方法可能有点奇怪。我参加的一门Java初级课程提到,在一个方法检索一个数字(
nextDouble()
,例如)之后,在行尾有一个新行字符。下次使用nextLine()
时,它会将新行字符作为输入读取,而不会给您键入任何内容的机会如果你在循环前加一个
nextLine()
来询问课程名称它会通过那条新的线。任何后续的
nextLine()
调用实际上都会让您提供输入。也就是说,你也需要在字母等级循环之前这样做因为你在循环之前也会问数字
这对我有用。希望有帮助
# 2 楼答案
尝试使用:
及
在
for
循环中扫描字符串。 而不是及
有关更多详细信息,请参见this link: