我不断收到此错误:我正在为类创建的Mad Lib中的线程“ main” java.util.InputMismatchException中的异常。我不是在问如何使代码更好,而是为什么它不会起作用。我只会在第三个形容词之后收到此通知。这是我的代码:
import java.util.Scanner;
public class scanner_practice {
public static void main(String[] args) {
// Housekeeping
Scanner kb = new Scanner(System.in);
String word, story;
int intVar;
double dubVar;
// Introduction
System.out.println("Hi there! I have a great story to tell, but I don't remember some of the words.");
System.out.println("Will you help me? Hooray! Thank you! Here we go...");
// Instructions
System.out.println("\nWhen I ask you for a word or number, just type it. I'll handle the rest.");
// Collect values and bulid the story
System.out.print("Verb: ");
word = kb.next();
story = "I am Dr. Pink and I am destined to " + word;
System.out.print("Adjective: ");
word = kb.next();
kb.nextLine(); // Stops the program skipping
story += "the world! Unfortunately the \n" + "world is full of " + word;
System.out.print("Plural noun: ");
word = kb.nextLine();
story += " " + word;
System.out.print("Adjective: ");
word = kb.next();
story += "that do not agree. So this is \n" + "my " + word;
System.out.print("Adjective: ");
intVar = kb.nextInt();
story += " plan: To start with, I'll need to build my " + intVar;
System.out.print("Adjetive ");
word = kb.next();
story += " hideout in an /n" + "abandoned " + word;
System.out.print("Company Name: ");
word = kb.next();
story += " complex in the middle of the" + word;
System.out.print("Type of Place: ");
word = kb.next();
story += ". All \n" + "the " + word;
System.out.print("Adjective: ");
word = kb.next();
story += "will address me as 'The Great and " + word;
System.out.print("Occupation (plural): ");
word = kb.next();
kb.nextLine(); // Stops the program skipping
story += " Dr. Pink.' I will \n" + "hire some " + word;
System.out.print("Plural event): ");
word = kb.nextLine();
story += "to design a machine to trigger \n" + "a huge " + word;
System.out.print("Plural noun: ");
word = kb.next();
story += " whenever I want it to. And if they don't want to build it, I \n" + "will capture their " + word;
System.out.print("Something you hate doing: ");
word = kb.next();
story += " and threaten to make them " + word + "for hours on end. \n" + "Muwahahahahaha!";
// Print out the story
System.out.println(story);
}
}
我需要解决什么?这是今晚的事情……所以,如果我能迅速得到答案,那对我来说意味着世界!谢谢你!
答案 0 :(得分:0)
学习如何进行错误排查与学习如何编码:-)
几乎一样重要A。首先查看the docs for InputMismatchException,以获取发生时间和原因的线索:
由扫描程序抛出以表明检索到的令牌没有 匹配预期类型的模式,或者令牌超出了预期类型的范围。
B。查看完整的堆栈跟踪。跟踪提供有关错误的上下文,例如发生错误的行以及正在调用的方法:
... at java.util.Scanner。 nextInt (Scanner.java:2076)
在scan_practice.main(scanner_practice.java: 41 )
C。查看错误行附近的Java代码:
line 40: System.out.print("Adjective: ");
结论:“形容词”可能不是整数。