扫描仪在for循环中跳过输入

时间:2015-09-16 23:20:30

标签: java arrays for-loop test-class

所以我有这段代码:

public class Subjects {
    String name;
    int period;
    char grade;

public void period()
{
    System.out.println("I have " + this.name + " during period " + this.period + ".");
}

public void study()
{
    if (this.grade == 'B')
    {
        System.out.println("I study for " +  this.name + ", so I get a B!");
    }
    else if (this.grade == 'A')
    {
        System.out.println("I study for " +  this.name + ", so I get an A!");
    }
    else
    {
        System.out.println("I don't study for " +  this.name + ", so I get a " + this.grade +". :(");
    }
}

}

这个测试类:

import java.util.Scanner;

public class SubjectsTest {
    public static void main (String [] args)
{
    Scanner kboard = new Scanner(System.in);
    Subjects[] classes;

    System.out.print ("How many classes do you have? ");
    int x = kboard.nextInt();
    int y;
    classes = new Subjects[x];

    for (int b = 0; b < x; b++) 
    {
        classes[b] = new Subjects();
    }

    for (int a = 0; a < x; a++)
    {
        y = a + 1;
        System.out.println("Period " + y );

        System.out.println ("Enter the subject name: ");
        classes[a].name = kboard.nextLine();
        System.out.println ("Enter your class period: ");
        classes[a].period = kboard.nextInt();
        System.out.println ("Enter your grade in the class: ");
        classes[a].grade = kboard.next().charAt(0);


    }

    for (int i = 0; i < x; i++)
    {
        classes[i].period();
        classes[i].study();
    }


}

}

用户应该输入他们拥有的课程数量(例如8),然后输入每个课程的名称,期限和等级。然后在最后,它为每个类打印2个语句。

但是,当我运行程序(在Eclipse中)时,在询问How many classes do you have?并且用户回答之后,系统会打印出接下来的两个问题而不等待第一个问题的答案。我的错误消息如下所示:

Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at SubjectsTest.main(SubjectsTest.java:27)

为什么这样做?我该如何解决?我是Java新手,所以非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

您应该在kboard.nextLine();来电之后加kboard.nextInt();来获得课程数量。

这将读取kboard.nextInt();行的其余部分,并允许读取您的主题名称以正常工作。目前,您在主题名称中读取的kboard.nextLine();正在读取输入的剩余部分中的类数。因此,当您尝试阅读主题时,它实际上正在等待int一段时间并为您提供该异常。

编辑:对于所有修改都很抱歉,这个问题的接受答案可能会更有意义:Using scanner.nextLine()