scan.nextLine doesn't work in a while loop.
When I put scan.nextLine in a while loop, it becomes a space the second time I go through it. I want it to read a quote even if I have a space but the side effect is that it doesn't read in what the user types in the second time if it's in a while loop. Can someone tell me how to fix this problem?
// *******************************************
// Palindrome.java
//
// Author: Andrew Date: 10/21/12
// *******************************************
import java.util.Scanner;
public class Palindrome
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
String again = ("Yes");
while (again.equalsIgnoreCase("Yes"))
{
int x = 0;
System.out.println("Please enter in a phrase.");
String phrase = scan.nextLine();
String phrase1 = phrase.toLowerCase();
while ((x<(phrase1.length()/2))&&
(phrase1.charAt(x)==
phrase1.charAt(phrase1.length()-1-x)))
{
x++;
}
if (x>=(phrase1.length()/2))
System.out.println("The phrase " + phrase
+ " is a palindrome.");
else
System.out.println("The phrase " + phrase +
" is not a palindrome.");
System.out.println("Please enter in Yes to " +
"test another phrase. " +
"Enter in No to quit the "
+ "palindrome test.");
again = scan.next();
}
}
}
Welcome to DrJava.
> java Palindrome
Please enter in a phrase.
[Stanley Yelnats]
The phrase Stanley Yelnats is a palindrome.
Please enter in Yes to test another phrase. Enter in No to quit the palindrome test.
[Yes]
Please enter in a phrase.
The phrase is a palindrome.
Please enter in Yes to test another phrase. Enter in No to quit the palindrome test.
[DrJava Input Box]
Re: scan.nextLine doesn't work in a while loop.
It sounds like you may have a potential buffer problem. At the end of your while loop, try making phrase equal to a blank phrase. It will clear the buffer and and help avoid any unnecessary inputs.
Re: scan.nextLine doesn't work in a while loop.
Quote:
Originally Posted by
ATL1994
When I put scan.nextLine in a while loop, it becomes a space the second time I go through it.
Code java:
while (again.equalsIgnoreCase("Yes"))
{
int x = 0;
System.out.println("Please enter in a phrase.");
String phrase = scan.nextLine();.
.
.
again = scan.next();
}
After you scan the "Yes" at the bottom of the loop, the line terminating character is still in the Scanner input stream. Then at the top of the loop, scan.nextLine() sees that and removes it from the input stream and returns an empty String.
Solution: use scan.nextLine() at the bottom of the loop (instead of scan.next()) to read the user input and to "flush" the input stream so that the input stream will have to wait for more user input the top of the loop.
Cheers!
Z