【发布时间】: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