Homework 6 (Mad Libs) FAQ
-
Q: How do I get started?
-
A: Read Ch. 6 in the textbook. Look over the TA Hours worked example from the textbook and slides, and the IMDB 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'snext
method. If you want to allow a multi-word answer, usenextLine
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 ofMyProgram.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 anint
. -
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 newScanner
over the sameString
to start reading over again. -
Q: How do I use a
PrintStream
? -
A: See section 6.4 of the textbook. You just construct it and then call methods on it such as
print
andprintln
, just like you do withSystem.out
. -
Q: How do I know which words are placeholders?
-
A: Any token that begins with a
<
and ends with a>
is a placeholder. -
How do I tell whether to print "a" or "an" for the prompt message? How do I change the
-
dashes in a placeholder into spaces? -
A: String objects have lots of useful methods that can help you with these tasks. Most of them are ones we have seen a lot already, such as
length
,startsWith
,substring
,toUpperCase
, and so on. You may also want to use thereplace
method on this assignment, which replaces all occurrences of one character with another. For example:String str = "mississippi"; str = str.replace("s", "*"); // str = "mi**i**ippi"
-
Q: How do I view an existing mad lib?
-
A: Just read the input file and output all of its contents to the console. See the textbook Chapter 6 Self-Check problem #12,
printEntireFile
, for hints. -
Q: How do I re-prompt if the input file is not found?
-
A: See the methods of
File
objects shown in the lecture slides. You can use these methods to detect whether or not a file exists and re-prompt if it does not.