我正在尝试创建一个简单的控制台程序,询问用户是否要创建列表,如果"is",则允许他们输入列表的名称。然后它应该在退出程序之前“打印”列表的名称。
对于第一部分,我的代码允许用户说y
或n
,但在我的条件语句中它不允许用户输入列表的名称;它只是完成了程序。没有错误信息;它只是没有按我的预期运行。这是我的代码:
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")
}
在此先感谢您抽出宝贵时间提供帮助!
最佳答案
改变
answer = (char) br.read();
到
answer = (char) br.read();br.readLine();
为了在用户按下y
或n
后读取换行符
完整代码:
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")
}
}
输出:
Would like to create a list (y/n)?
y
Enter the name of the list:
Mylist
The name of your list is: Mylist
这是您期望的输出吗?
关于Java 控制台程序不让我输入字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14799397/