0

我在这里遇到了这个 do-while 循环的问题。第一次运行顺利,但第二次询问国家后,它不会让我输入。有什么帮助吗?

import java.util.*;

public class UseList
{
public static void main(String[] args)
{
    Scanner userInput = new Scanner(System.in);        
    ListInterface<String> list = new ArraySortedList<String>();
    String country, flag;
    char flagCharred;

    do
    {            
        System.out.print("Enter a country you've visited: ");
        country = userInput.nextLine();
        list.add(country);

        System.out.print("\n" +list);

        System.out.print("\nAdd another country?: Y/N ");
        flag = userInput.next();
        flagCharred = flag.charAt(0);
    } 
while (flagCharred == 'y' || flagCharred == 'Y');
}
}
4

2 回答 2

3

next doesn't consume the end of line, so it'll be consumed in the next nextLine.

For example, when you write Y as the second input, you are actually writing Y and pressing enter, which is the '\n' character, the next will read the Y and the '\n' will be the input for the nextLine causing it so skip the "real" input you wanted.


One solution is to change next to nextLine.

于 2013-10-29T07:22:02.300 回答
0

这是您问题的解决方案

导入 java.util.ArrayList;

导入 java.util.List;

导入 java.util.Scanner;

公共类 UseList {

公共静态无效主要(字符串[]参数){

Scanner userInput = new Scanner(System.in); 

List<String> list = new ArrayList<String>();

String country, flag;

char flagCharred;

do
{            
    System.out.print("Enter a country you've visited: ");
    country = userInput.nextLine();
    list.add(country);

    System.out.print("\n" +list);

    System.out.print("\nAdd another country?: Y/N ");
    flag = userInput.next();
    flagCharred = flag.charAt(0);
    country = userInput.nextLine();

} 

而 ('y'==flagCharred || 'Y'==flagCharred);

}

}

于 2013-10-29T07:37:39.953 回答