gpt4 book ai didi

Java 扫描器跳过迭代

转载 作者:行者123 更新时间:2023-12-01 09:37:38 24 4
gpt4 key购买 nike

我现在被一个问题困扰了一段时间,并且该程序没有执行我认为它应该执行的操作。

当我运行程序并到达要求您提供类(class)名称的部分时,程序会跳过第一次迭代或其他迭代,具体取决于输入的类(class)数量。它只允许最后一次迭代的输入。对于以下 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.

最佳答案

nextLine() Scanner 方法可能有点奇怪。我参加的一门 Java 入门类(class)提到,在检索数字的方法(例如 nextDouble())之后,行尾会出现一个换行符。下次您使用 nextLine() 时,它会读取该换行符作为输入,而不给您输入任何内容的机会。

如果您在询问类(class)名称的循环之前放置 nextLine()

kb.nextLine(); // <-- here
for(int i = 0; i < course.length; i++)
{
System.out.println("What is the name of course #" + (i + 1));
courseNumber[i] = kb.nextLine();
}

它将通过该新行。任何后续 nextLine() 调用实际上都会让您提供输入。也就是说,您还需要在字母成绩循环之前执行此操作,

kb.nextLine(); // <-- here
for(int i = 0; i < course.length; i++)
{
System.out.println("What is the final letter grade for " + courseNumber[i]);
letterGrade[i] = kb.nextLine();
}

因为您在此循环之前也要求输入数字。

这对我有用。希望对您有帮助!

关于Java 扫描器跳过迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38726425/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com