这段代码一直返回 0 而不是增加大小?
我想做的是:
提示用户输入列表大小(例如,N = 10,000)。以随机顺序创建从 1 到 N 的整数的 ArrayList。
这是我到目前为止所拥有的,但列表只返回数字 0 n 次
System.out.print("Please enter a list size: ");
Scanner ST = new Scanner(System.in);
int n= ST.nextInt();
List<Integer> myList = new ArrayList<Integer>(n);
for ( int i = 1; i<(n+1); i++){
int k = 0;
k = k + 1;
myList.add(k);
}
What I am trying to do is:
Prompt the user for a list size (e.g., N = 10,000). Create an ArrayList of the Integers from 1 to N, in random order.
This is what I have so far, but the list just returns the number 0 n times
System.out.print("Please enter a list size: ");
Scanner ST = new Scanner(System.in);
int n= ST.nextInt();
List<Integer> myList = new ArrayList<Integer>(n);
for ( int i = 1; i<(n+1); i++){
int k = 0;
k = k + 1;
myList.add(k);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,因为您在循环内声明
k
。只需移至循环之前即可。目前,“新声明的”变量将在循环每次迭代的第一行被赋值为 0;然后它会在下一行增加到 1。然后,该值 (1) 将被装箱,并且返回值
Integer.valueOf(1)
将被添加到列表中。然后我们再次循环...另一种方法是只使用循环索引 - 可能同时将循环更改为更惯用的样式:
Yes, because you're declaring
k
inside the loop. Just moveto before the loop. Currently the "newly declared" variable will be assigned the value of 0 on the first line of each iteration of the loop; it will then be incremented to 1 on the next line. Then that value (1) will be boxed and the return value
Integer.valueOf(1)
will be added to the list. Then we go round again...An alternative is to just use the loop index - potentially changing the loop to a rather more idiomatic style at the same time: