如何在列中打印数组元素

时间:2016-09-20 02:27:34

标签: java arrays for-loop

我正在从文本文件exnames.txt

中读取名称
aaa bbb ccc ddd
bbb kkk zzz fff

代码就在这里,

try {
            BufferedReader br = new BufferedReader(new FileReader("XML/exnames.txt"));
            while (true) {          
                String line = br.readLine();                
                if (line == null) 
                    break;
            //  System.out.println(line);
                String[] data = line.split("\t");   
                for(int i=0;i<data.length;i++)
                    System.out.println(data[i] + data[i+1]);
            }
        }
        catch(Exception e)
        {
            System.out.println("error "+e);
        }

我希望按照以下顺序打印

aaa bbb
aaa ccc
aaa ddd
bbb kkk
bbb zzz
bbb fff

重复第一个元素并从第二个元素开始循环 如果我使用array [i] + array [i + 1]给出索引绑定异常,请帮助。

2 个答案:

答案 0 :(得分:0)

如果你想在每一行打印data的第一个元素,加上当前元素,试试这个:

for (int i = 1; i < data.length; i++) { // loop starting on 1 (the second element)
    System.out.println(data[0]+" "+data[i]); // first element + space + current element
}

这将在概念上打印:

data[0] data[1]
data[0] data[2]
data[0] data[3]
...

答案 1 :(得分:0)

//遍历您的列表

for (int i = 1; i < data.length; i++) {
    System.out.println(data[i-1]+" "+data[i]); 
// first and second element is printed
    System.out.println(data[i-1]+" "+data[i+1]); 
// first and third element is printed
    System.out.println(data[i-1]+" "+data[i+2]); 
// first and fourth element is printed
}