0

所以我有这个代码:

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 新手,所以任何帮助将不胜感激!

4

1 回答 1

1

你应该kboard.nextLine();在你的kboard.nextInt();电话后面加上一个得到班级数量的号码。

这将读取该kboard.nextInt();行的其余部分,并允许读取您的主题名称以正常工作。目前,您kboard.nextLine();要阅读的主题名称是阅读您输入的其余部分以获取班级数量。因此,当您尝试阅读该主题时,它实际上是在等待intfor 期间并给您例外。

编辑:对不起所有的编辑,这个问题的接受答案可能更有意义:使用scanner.nextLine()

于 2015-09-16T23:27:51.627 回答