【问题标题】:Scanner skips input in a for loop [duplicate]扫描仪在 for 循环中跳过输入[重复]
【发布时间】:2015-12-13 17:32:33
【问题描述】:

所以我有这个代码:

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 新手,非常感谢任何帮助!

【问题讨论】:

  • 它似乎正在尝试获取 int 以分配给期间,但您没有输入 int

标签: java arrays for-loop test-class


【解决方案1】:

你应该在你的 kboard.nextInt(); 调用之后加上一个kboard.nextLine(); 来获取类的数量。

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

编辑:抱歉所有的编辑,这个问题的公认答案可能更有意义:Using scanner.nextLine()

【讨论】:

  • 谢谢!完美运行!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-09
  • 2013-01-31
  • 2018-05-03
相关资源
最近更新 更多