以相反的顺序打印ArrayList的元素

时间:2014-02-18 22:59:39

标签: java arraylist

我收到了一个文本文件,内容如下:

aaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbb
ccccccccccccccccccc
ddddddddddddddddddd

我必须让程序按以下顺序显示:

ddddddddddddddddddd
ccccccccccccccccccc
bbbbbbbbbbbbbbbbbbb
aaaaaaaaaaaaaaaaaaa

到目前为止,这是我的代码:

public class LineReverserMain {

    public static void main(String[] args) throws FileNotFoundException
    {

        int lineCount = 0;
        ArrayList <String> LinesArray = new ArrayList<String>( );            

        Scanner in = new Scanner(System.in);
        System.out.print("Please enter the file name: ");
        String filename = in.next();
        File file = new File(filename);           

        Scanner inFile = new Scanner(file);           

        while (inFile.hasNextLine()){                 
            lineCount += 1;                
            String CurrentLine = inFile.nextLine();              
            LinesArray.add(CurrentLine);
        }            

        System.out.println(LinesArray);
        System.out.println(lineCount + " lines");

        for(int linesCount = lineCount; linesCount>=0; linesCount = linesCount - 1){
            System.out.println(LinesArray.get(linesCount));
        }            
    }
}

但这似乎不起作用。

2 个答案:

答案 0 :(得分:1)

问题是你的for循环结束了。目前,lineCount是您拥有的行数,但ArrayList的有效索引介于0lineCount - 1之间。您必须获得IndexOutOfBoundsException

linesCount下面开始lineCount变量。变化

for(int linesCount = lineCount; linesCount>=0; linesCount = linesCount - 1){

for(int linesCount = lineCount - 1; linesCount>=0; linesCount = linesCount - 1){

答案 1 :(得分:0)

这是一个可以用堆栈解决的经典问题:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import java.util.Stack;

public class LineReverserMain {

    public static void main(String[] args) throws IOException {

                    // Linecounter and stack initialization
        int lineCount = 0;
        Stack<String> stack = new Stack<String>();

                    // Scaner and Filereader initialization
        Scanner s = new Scanner(System.in);
        System.out.print("Please enter the file name: ");
        String filename = s.next();
        File file = new File(filename);

                    // Push every read line onto the stack
        BufferedReader in = new BufferedReader(new FileReader(file));
        while (in.ready()) {
            stack.push(in.readLine());
            lineCount++;
        }

                    // While the stack isn't empty get the top most element
        while (!stack.isEmpty())
            System.out.println(stack.pop());
        System.out.println(lineCount);

                    // Close the Scanner and FileReader
        s.close();
        in.close();
    }
}

堆栈具有FILO结构,因此您可以在其上保存String并在之后弹出它们并获得正确的顺序。也许你对这个较短的解决方案感兴趣。