简体   繁体   English

ArrayList get()方法不返回第一个索引值

[英]ArrayList get() method not returning first index value

I created an arrayList to store String values.When i am going to fetch values from my arrayList it doesn't return me the first value of it;s 0th index. 我创建了一个arrayList来存储String值。当我要从arrayList中获取值时,它不会向我返回它的第一个值;第0个索引。

ArrayList<String> arrayList = new ArrayList<String>();
Scanner scan= new Scanner(System.in);
int noInput=scan.nextInt();

for(int i=0; i < noInput/2; i++)
   arrayList.add(scan.nextLine());       

for(int i=0;i<arrayList.size();i++)
   System.out.println("ArrayList:"+arrayList.get(i) + " "  + i );

使用scan.next()而不是scan.nextLine()

Because Scanner#nextInt reads only the int value, then nextLine in the first iteration will consume the remaining \\n (the enter you hit after you entered the integer value). 由于Scanner#nextInt 读取int值, nextLine ,第一次迭代中的nextLine将消耗剩余的\\n (输入整数值后命中的输入)。

To fix this, add nextLine after nextInt or use next instead of nextInt . 要解决此问题, nextLinenextInt之后添加nextLine ,或使用next代替nextInt

It is probably because your list is never filled. 可能是因为您的清单从未填满。 I think the first loop isn't gone into, so nothing is added to the array. 我认为第一个循环没有进入,因此没有添加任何数组。
for(int i=0; i < noInput/2; i++) arrayList.add(scan.nextLine());

Try debugging it or printing the size of the arraylist 尝试调试它或打印arraylist的大小

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM