2013-10-29 156 views
0

我在这里执行此循环时遇到问题。它第一次顺利运行,但在它第二次要求一个国家后,它不会让我投入。任何帮助?执行循环跳过代码

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'); 
} 
} 
+0

下()只读取一个字,而不是整个线。尝试使用nextLine(),因为这似乎是你的意思。 –

回答

3

next消耗线的末端,所以它会在未来nextLine消耗。

例如,当你写Y作为第二输入,你实际上是写Y并按进入,这是'\n'人品,next将读取Y'\n'将是nextLine输入引起它会跳过你想要的“真实”输入。


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

0

这是您的问题的解决方案

import java.util.ArrayList;

import java.util.List;

import java.util.Scanner;

公共类UseList {

公共静态无效的主要(字串[] 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(); 

} 

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

}

}