2014-11-16 145 views
1

我遇到的問題是,當輸入哨兵之前有偶數量的輸入時,它只輸出偶數字符串(例如:是,否,-1將打印否),並在那裏是一個奇數的輸入量,即使使用了哨兵,程序也會繼續運行。字符串ArrayList和輸出

//takes words (strings) from the user at the command line 
//returns the words as an ArrayList of strings. 
//Use a sentinel to allow user to tell the method when they are done entering words. 

public static ArrayList<String> arrayListFiller(){ 
    ArrayList<String> stringArrayList = new ArrayList(); 
    System.out.println("Enter the Strings you would like to add to the Array List."); 
    System.out.println("Type -1 when finished."); 
    Scanner in = new Scanner(System.in); 
    while(!in.nextLine().equals("-1")){ 
     String tempString = in.nextLine(); 
     stringArrayList.add(tempString); 
    }  
    return stringArrayList; 
} 

public static void printArrayListFiller(ArrayList<String> stringArrayList){ 
    for(int i = 0; i < stringArrayList.size(); i++){ 
     String value = stringArrayList.get(i); 
     System.out.println(value); 
    } 
} 

回答

1

我覺得你的問題在於你打電話給nextline過多次。如果你看看這些代碼行,

while(!in.nextLine().equals("-1")){ 
     String tempString = in.nextLine(); 
     stringArrayList.add(tempString); 
    }  

說我想輸入「鮑勃」,然後-1退出。你正在做的是讀「鮑勃」來測試它不是哨兵,但是你正在閱讀哨兵並將其添加到集合中(我甚至測試它是哨兵值)

我的解決方法是隻調用nextLine方法一次,然後在獲取它並對其進行處理時對其進行測試。要做到這一點,你必須有while循環外的局部變量,並將其分配給nextLine(),也就是

String temp 
while(!(temp=in.nextLine()).equals("-1")) { 
     .add(temp) 
} 

這樣,您就可以測試你正在閱讀的行不是標記值你有一種方法將它添加到集合中。 希望有幫助

+1

哈哈,你也可以用upvote打我嗎?欣賞愛情。我需要一些點讓我擺脫這個問題禁令 – committedandroider

+1

我會盡快解決您的問題。我對這個網站相當陌生,所以在獲得15的聲譽之前,我不能讓它滿意。再次感謝您的幫助。 – Evan

+1

謝謝!!!!!! – committedandroider