我有一个充满名称的数组。我使用for循环来打印我的名字,但是问题是我想打印2个名字:i(the name) and i+1 (the next name)
。您可能不明白我的意思,请看一下我的代码:
“文本”是我的textview,而“人”是数组:
people = new ArrayList<>();
people.add("Sam");
people.add("John");
people.add("Kim");
people.add("Edison");
for (int i=0; i< people.size(); i = i+2) {
text.append(people.get(i) + " with " + people.get(i+1));
}
(这些是数组中的名称:“ Kim”,“ John”,“ Sam”,“ Edison”)
Kim和Kim Sam以及Sam
金与约翰·山姆与爱迪生
答案 0 :(得分:0)
您的代码似乎对我有用,请检查您的数组是否还可以。
public class HelloWorld{
public static void main(String []args){
String[] names = {"Vikas","Kumar","Rajat","Ghator"};
for (int i=0; i< names.length; i = i+2) {
System.out.println(names[i] + " with " + names[i+1]);
}
}
}
打印:
与Kumar的维卡斯
与Ghator的拉贾特
答案 1 :(得分:0)
我只是尝试了一下,并且效果很好。
TextView tv = findViewById(R.id.textView);
String[] people = {"Kim","John","Sam","Edison"};
for (int i=0; i< people.length; i = i+2) {
tv.append(people[i] + " with " + people[i+1]+"\n");
}
如果您使用列表,则
List<String> people = new ArrayList<>();
people.add("Kim");
people.add("John");
people.add("Sam");
people.add("Edison");
for (int i=0; i< people.size(); i = i+2) {
tv.append(people.get(i) + " with " + people.get(i+1)+"\n");
}
输出:
和约翰一起金
山姆与爱迪生