2017-02-21 132 views
0

如果有人能向我解释如何可以得到这两个阵列彼此相邻,将不胜感激打印。如何打印两个增强的for循环彼此相邻,以

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循环中使用的变量未被初始化。

+1

不能并行运行两个如你所愿。你必须使用两个'迭代器' –

+0

问题不在于增强for循环,而是在使用并行数组的代码设计中。这是你为什么要避免使用并行数组而是创建一个同时包含两个字符串的类的又一个原因。 –

+0

谢谢大家我明白了,我只是想学习和探索增强型for循环,因为我是初学者。 – Conner

回答

1

你可以在这种情况下,使用常规的for循环,这样就可以指数双双的阵列。您必须确保两个阵列的长度相同。

for (int i = 0; i < names.length; i++){ 
    System.out.println(names[i] + " " + pets[i]); 
} 

我不太喜欢使用并行阵列这样的,因为它通常指向一个设计问题。如果你有相关的数据,那么你应该创建一个能够保持一致的类。

这里是一个Pet类。现在

class Pet { 
    private String name; 
    private String type; 

    public Pet(String name, String type) { 
     this.name = name; 
     this.type = type; 
    } 

    public String getName() { 
     return name; 
    } 

    public String getType() { 
     return type; 
    } 
} 

你可以遍历的Pet阵列(或更好,列表)。

List<Pet> pets = new LinkedList<Pet>(); 
pets.add(new Pet("Spot", "dog")); 
// add all the pets 

for(Pet pet : pets) { 
    System.out.println(pet.getName() + " " + pet.getType()); 
} 
0

下面的解决方案将工作,但只有在阵列是相同的大小。您可以使用的另一个解决方案是一个迭代器。

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 (int i = 0; i < names.length; i++){ 
     System.out.println(names[i] + " " + pets[i]); 
    } 
    } 

} 
1

试试这个:

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 
1

我不相信阵列是相同的长度,所以我建议你通过两种情况:循环我将小于两个阵列的长度。这将确保你永远不会触及arrayoutofbound例外

for (int i = 0; i < names.length && i < pets.length; i++){ 
     System.out.println(name[i] + " " + pets[i]); 
}