do-while循环跳过代码

时间:2013-10-29 07:19:56

标签: java loops

我在这个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');
}
}

2 个答案:

答案 0 :(得分:3)

next 不会消耗行尾,因此会在下一个nextLine中使用它。

例如,当您将Y写为第二个输入时,您实际上是在写Y并按输入,这是'\n'个字符, next将会读取Y,而'\n'将成为nextLine的输入,因此请跳过&#34;真实的&#34;输入你想要的。


一种解决方案是将next更改为nextLine

答案 1 :(得分:0)

这是您的问题的解决方案

import java.util.ArrayList;

import java.util.List;

import java.util.Scanner;

公共类UseList {

public static void main(String [] args) {

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();

} 

while(&#39; y&#39; == flagCharred ||&#39; Y&#39; == flagCharred);

}

}

相关问题