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

問題は read() です。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 に答える