Question
/*Using instructions from the accompanying WORD document, use this program to explore the problems with, and effective utilization of, the next() and nextLine() methods of
/*Using instructions from the accompanying WORD document, use this program to explore the problems with, and effective utilization of, the next() and nextLine() methods of the String class.*Note that the intention of this class is that you enter the number 3, followed by the phrase blind mice, then print them out to yield the phrase 3 blind mice.*/
import java.util.Scanner;
class Main {
public static void main (String[] args){
int num1;
String alpha, beta;
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
num1 = input.nextInt();
//beta = input.nextLine();
System.out.println("Enter a word: ");
alpha = input.nextLine();
System.out.println(num1 + " " + alpha);
input.close();
}
}
Three Blind Mice - playing with Strings and numbers
This activity demonstrates the unique capabilities and problems with the next() and nextLine() methods of entering Strings.
Follow the exercises below to identify those problems. You will discover workarounds as well.
After that you will read a section of the textbook that discusses the phenomena you discovered.
Program exercises:
1. Creat a class called ThreeBlindMice and copy/paste the text file with that name into the class.
2. Run the program. Enter 3 for the number, then blind mice as the phrase.
What went wrong? What data were you not able to enter?
3. In the line where you enter alpha (line 15), change the method nextLine() to the method next().
What could you do thi time that you couldn't do before?
Still, it didn't work completely right. What went wrong?
4. Run the program again, entering blindmice as if it were a single word.
It worked, didn't it?
Wouldn't it be nice if we could print blind mice as 2 separate words? See step 5.
5. Now un-comment the line starting with "beta". Then reset the "alpha" line to use nextLine() method instead of the next() method.
Run the program again. This time everything worked fine, right?
Now let's find out why this was the only combination that worked.
Reading:
Read the paragraph at the top of page 82.
What is the problem with using nextLine() after reading a numeric value?
What is the fix for this problem?
In this program, what line read the end-of-line character?
The book does not mention a limitation of the next() method but you found one in step 3 - It only reads to the first ________.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started