0

このループが最初に繰り返されるときはうまく機能しますが、繰り返すために文字「y」を押した後、次に表示されるときは、別の名前を入力できません。これの原因はわかりませんが、入力バッファをクリアする必要がある場合はCを思い出します。

どんな助けでも確かにありがたいです。

byte counter = 1;
boolean myCondition = false;
List<String> myList = new ArrayList();
BufferedReader objReader = new BufferedReader(new InputStreamReader(System.in));

do{
    System.out.println("Enter the #" +counter +" person's name:");
    // low quality validation
    String dude = objReader.readLine();

    while (myList.contains(dude)){
        System.out.println("Man, this dude:" +dude +" is already loaded into the List! Pick another name:\n");
        dude = objReader.readLine();            
    }

    myList.add(dude);
    counter++;
    System.out.println("Would you like to add another name to the list? yes/no");

    char myChar = (char) System.in.read();

    if (myChar == 'y' || myChar == 'Y')
        myCondition = true;
    else
        myCondition = false;

    } while (myCondition);
4

4 に答える 4

2

あなたのコードを見てください:

  1. あなたは文字「y」を読みます
  2. char myChar = (char) System.in.read();押すまで待ち​​ますEnter
  3. myCharは「y」になりました。これにより、'\ n'( `Enter')がバッファに残ります
  4. 次にString dude = objReader.readLine();、すでにバッファに存在する'\n'で終わる行を読み取ります。

単純な代わりに行全体を読む必要がありますread()

yの解像度を上げたい場合:

String line = objReader.readLine();
myCondition = line.startsWith("Y") || line.startsWith("y");
于 2012-05-16T17:36:59.747 に答える
0

BufferedReader objReader = new BufferedReader(new InputStreamReader(System.in));do/whileループ内を移動してみてください。そのように、毎回再初期化する必要があります。

于 2012-05-16T17:27:43.437 に答える
0

これを試して、

System.out.println("Would you like to add another name to the list? yes/no");
Scanner scan = new Scanner(System.in);
String myChar = scan.nextLine();

if (myChar.equals("y") || myChar.equals("Y"))
    myCondition = true;
else
    myCondition = false;
于 2012-05-16T17:48:07.003 に答える
0

スキャナーと他のいくつかのマイナーなコード変更を使用して正常に動作します。

 byte counter = 1;
            boolean myCondition = false;
            Scanner scan = new Scanner(System.in);
            List<String> myList = new ArrayList();

            do{
                  System.out.println("Enter the #" + counter + " person's name:");
                  // low quality validation
                  String dude = scan.nextLine();
                  while (myList.contains(dude)) {
                    System.out.println("Man, this dude:" + dude + " is already loaded into the List! Pick another name:\n");
                  }
                  myList.add(dude);
                  counter++;
                  System.out.println("Would you like to add another name to the list? yes/no");
                  String choice = scan.nextLine();
                  if (choice.equalsIgnoreCase("Y")) {
                    myCondition = true;
                  } else {
                    myCondition = false;
                  }

             } while (myCondition);

プログラムを終了する前に、それを実行して合計7つの名前を入力しました。

于 2012-05-16T17:56:05.177 に答える