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

时间:2013-02-10 15:39:21

标签: java console-application bufferedreader conditional-statements

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

我的代码允许用户为第一部分说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")
    }

提前感谢您的时间和帮助!

3 个答案:

答案 0 :(得分:4)

更改

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

这是您期望的输出吗?

答案 1 :(得分:2)

问题是读()。它不会读取由于Enter而出现的newLine。

 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.

答案 2 :(得分:0)

...
String answer = br.readLine ();
if (answer.startsWith ("y")) {
...