Java 控制台程序不让我输入字符串

标签 java console-application bufferedreader conditional-statements

我正在尝试创建一个简单的控制台程序,询问用户是否要创建列表,如果"is",则允许他们输入列表的名称。然后它应该在退出程序之前“打印”列表的名称。

对于第一部分,我的代码允许用户说yn,但在我的条件语句中它不允许用户输入列表的名称;它只是完成了程序。没有错误信息;它只是没有按我的预期运行。这是我的代码:

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();

为了在用户按下yn后读取换行符

完整代码:

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/

相关文章:

java - onClickListener 无法在 Fragment 中工作

java - java中如何使用Ghost对象实现延迟加载?

java - 无法使用 Maven 编译简单的 Java 10/Java 11 项目

java - 使用线程计算不同单词的数量

java - 为什么在这种情况下使用 BufferedReader?

java - Netbeans org.apache.poi - 无法访问 Date1904Support

c# - 将控制台行写入文件

c# - asp.net中web应用程序需要的调度作业思路

c# - 将文件路径传递给 Main(string[] args) 不起作用

java - 为什么这个基本的客户端-服务器程序不传递数据?