3

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

我的代码允许用户说yor 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")
    }

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

4

3 回答 3

4

改变

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

这是您期望的输出吗?

于 2013-02-10T15:41:02.850 回答
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.
于 2013-02-10T15:48:55.843 回答
0
...
String answer = br.readLine ();
if (answer.startsWith ("y")) {
...
于 2013-02-10T15:47:19.977 回答