如果有人可以向我解释如何让这两个数组彼此相邻打印,我将不胜感激。
package labs;
import java.util.Arrays;
public class ArrayOfObjects {
public static void main (String[] args){
String[] pets = {"dog", "cow", "sheep", "cat", "horse"};
String[] names = {"Spot", "Milky", "Bahhhhd", "Meooooow", "Nayyybor"};
for (String name : names){
System.out.println(name.toString());
}
for (String type : pets){
System.out.println(type.toString());
}
}
}
我得到的输出显然是
Spot
Milky
Bahhhhd
Meooooow
Nayyybor
dog
cow
sheep
cat
horse
但是......我想要
Spot dog
Milky cow
Bahhhhd sheep
Meooooow cat
Nayyybor horse
我尝试的一件事是更改两个增强的 for 循环并在其中使用 toString 方法,但没有让它打印数组,但是当我在不同的 for 循环中打印这两个数组时我在增强 for 循环中使用的变量未初始化。
最佳答案
试试这个:
public static void main(String[] args) {
String[] pets = {"dog", "cow", "sheep", "cat", "horse"};
String[] names = {"Spot", "Milky", "Bahhhhd", "Meooooow", "Nayyybor"};
for(int i=0; i<pets.length; i++) {
System.out.println(names[i] + " " + pets[i]);
}
}
输出是:
Spot dog
Milky cow
Bahhhhd sheep
Meooooow cat
Nayyybor horse
关于java - 如何按顺序打印两个相邻的增强型 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42380172/