2014-11-16 147 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