2016-08-02 70 views
0

我一直在一个问题上停留了一段时间,程序没有做我认为应该做的事情。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< 
    } 
    } 
} 

P.S.这是我的工作的问题:

写具有以下输入,所有这些都存储在 阵列(大小为5)的程序。首先,该学期学生参加了多少门课程 (不能大于5)。在每个学生的ARRAYS中存储 课程编号/名称(例如ICT 435),学分(1-4)和 字母等级(A-F)。确定学期的GPA。

+2

在使用next(),nextInt()或其他nextFoo()方法之后跳过nextLine()(http:// stackoverflow。com/questions/13102045/skip-nextline-after-using-next-nextint-or-other-nextfoo-methods) – Arjan

+0

@Edù你可以接受答案,如果它解决了你的问题。 – Kaushal28

回答

0

尝试使用:

courseNumber[i] = kb.next(); 

letterGrade[i] = kb.next(); 

for循环在扫描字符串。 而不是

courseNumber[i] = kb.nextLine(); 

letterGrade[i] = kb.nextLine(); 

看到this link了解更多详情:

1

nextLine()Scanner方法可以是一种奇怪的。我在开始的一门Java课程中提到,在检索一个数字(例如,nextDouble())之后,在行末有一个新的行字符。下次您使用nextLine()时,它会将新行字符作为输入,而不是给您输入任何内容的机会。

如果你把一个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()调用实际上都会让您提供输入。也就是说,您还需要在信件等级循环之前执行此操作,因为您在该循环之前也要求提供数字,所以请在信件等级循环之前执行此操作。

这对我有效。希望能帮助到你!