Java console program preventing me from entering string
I am trying to create a simple console program that asks the user if they want to create a list and if so, let them enter the name of the list. Then it should "print" the list name before exiting the program.
My code allows the user to speak y
or n
, for the first part, but in my conditional, it does not allow the user to enter the name of the list; it just ends the program. No error message; it just doesn't function as I expected. Here is my code:
public static void main(String[] args) throws IOException
{
getAnswers();
}
public static void getAnswers()throws IOException{
char answer;
String listName;
BufferedReader br = new BufferedReader
(new InputStreamReader(System.in));
System.out.println ("Would like to create a list (y/n)? ");
answer = (char) br.read();
***if (answer == 'y'){
System.out.println("Enter the name of the list: ");
listName = br.readLine();
System.out.println ("The name of your list is: " + listName);}***
//insert code to save name to innerList
else if (answer == 'n'){
System.out.println ("No list created, yet");
}
//check if lists exist in innerList
// print existing classes; if no classes
// system.out.println ("No lists where created. Press any key to exit")
}
Thanks in advance for your time and we will help with this!
source to share
Change
answer = (char) br.read();
To
answer = (char) br.read();br.readLine();
To read a new line after clicking by the user, y
orn
Complete code:
import java.io.*;
class Test {
public static void main(String[] args) throws IOException {
getAnswers();
}
public static void getAnswers() throws IOException {
char answer;
String listName;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println ("Would like to create a list (y/n)? ");
answer = (char) br.read();
br.readLine(); // <-- ADDED THIS
if (answer == 'y'){
System.out.println("Enter the name of the list: ");
listName = br.readLine();
System.out.println ("The name of your list is: " + listName);
}
//insert code to save name to innerList
else if (answer == 'n') {
System.out.println ("No list created, yet");
}
//check if lists exist in innerList
// print existing classes; if no classes
// system.out.println ("No lists where created. Press any key to exit")
}
}
Ouput:
Would like to create a list (y/n)?
y
Enter the name of the list:
Mylist
The name of your list is: Mylist
Is this the result you expect?
source to share
The problem is read (). it doesn't read the newLine that comes from Enter.
answer = (char) br.read(); // so if you enter 'y'+enter then -> 'y\n' and read will read only 'y' and the \n is readed by the nextline.
br.readLine(); // this line will consume \n to allow next readLine from accept input.
source to share