0

这个循环第一次迭代效果很好,但是在我按下 char '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

Look at your code:

  1. You read character 'y'
  2. The char myChar = (char) System.in.read(); waits until you press Enter
  3. myChar is now 'y'. This leaves '\n' (`Enter') in buffer
  4. Next String dude = objReader.readLine(); reads line ended by '\n' that is present already in buffer.

You should read whole line instead simple read()

If you want better resolution of y:

String line = objReader.readLine();
myCondition = line.startsWith("Y") || line.startsWith("y");
于 2012-05-16T17:36:59.747 回答
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);

在退出程序之前,我运行它并输入了总共七个名称。

于 2012-05-16T17:56:05.177 回答
0

尝试BufferedReader objReader = new BufferedReader(new InputStreamReader(System.in));在你的 do/while 循环中移动。每次都应该重新初始化它,那样。

于 2012-05-16T17:27:43.437 回答