【发布时间】:2015-03-10 06:29:08
【问题描述】:
我正在做一个关于列表的初学者 Java 教程,并遇到以下问题
// 1) Declare am ArrayList of strings
// 2) Call the add method and add 10 random strings
// 3) Iterate through all the elements in the ArrayList
// 4) Remove the first and last element of the ArrayList
// 5) Iterate through all the elements in the ArrayList, again.
下面是我的代码
import java.util.ArrayList;
import java.util.Random;
public class Ex1_BasicArrayList {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i <= 10; i++){
Random rand = new Random();
String alphabet = "abcdefghijklmnopqrstuvwxyz";
StringBuilder sb = new StringBuilder();
sb.append(alphabet.charAt(rand.nextInt(alphabet.length())));
String randy = sb.toString();
list.add(randy);
}
for (int i = 0; i < list.size(); i++){
System.out.print(list.get(i));
}
list.remove(0);
list.remove(list.size()-1);
for (int i = 0; i < list.size(); i++){
System.out.println(list.get(i));
}
}
}
我已经设法生成了一个输出,但它不正确:(
对于我的第一个 System.out.print(list.get(i));,我试图获得 10 个字符串值的输出,但我得到了 12 个。
示例输出:nhgacqhlejph
当我运行第二个 System.out.println(list.get(i)); 时,我得到了 8 个字符串值的输出,如果我从列表中的 10 个开始,这是正确的,但我有 12 个,所以这意味着删除了 4 个值:/
样本输出:
g
a
c
q
h
l
e
j
有人知道我的代码哪里出错了吗?
重复:
我希望从第一个
System.out.print(list.get(i));中得到 10 个字符串值,每个字母都有一个字母我还想通过运行第二个
System.out.println(list.get(i));从原始列表中减少 2 个字符串值
【问题讨论】:
-
'int i = 0;我
-
你的第一个
for从i = 0循环到i = 10,你得到一个长度为11的字符串,但我不知道这12个字符是从哪里来的。 -
调试的一个好方法是摆脱随机性。而不是随机字符串(难以调试)将数字作为字符串 list.add(i + "");