2013-10-29 64 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);

}

}