Q: How do I get started?
A: Read Ch. 6 in the textbook. Look over the and Temperatures and Cities example from lecture.
Q: Why does my prompt get all messed up when the user types more than one word on the console?
A: Make sure to choose the right method(s) for reading user input. If you want a one-word answer, use the Scanner
object's next
method. If you want to allow a multi-word answer, use nextLine
instead.
Q: Why do I get a NoSuchElementException
?
A: You tried to read past the end of a Scanner
. Read the exception output text carefully and look for the first line that mentions your program. That's the line that is the culprit. For example, the output:
Exception in thread "main" java.util.NoSuchElementException at java.util.Scanner.throwFor(Scanner.java:838) at java.util.Scanner.next(Scanner.java:1347) at MyProgram.sillyMethod(MyProgram.java:39) at MyProgram.main(MyProgram.java:15)
means that there's an error in sillyMethod
at line 39 of MyProgram.java
.
Q: Why do I get an InputMismatchException
?
A: You tried to read the wrong type of token from a Scanner
. For example, you tried to read the word "Lisa" as an int
.
Q: How do I make a Scanner
start over or go back?
A: You can't! But if it is a String Scanner
, you can make a new Scanner
over the same String
to start reading over again.