在Java中按顺序输出句子

时间:2015-02-21 02:37:48

标签: java string file for-loop arraylist

我目前正在尝试获取此输出,其中文本文件中的句子按顺序排列:

0 : The cat in the hat
1 : The cat sat on the mat
2 : Pigs in a blanket

我将文本文件添加到ArrayList,目前无法显示上述输出。我知道问题出在for loop

的某个地方
public static void main(String[] args) throws FileNotFoundException{

        //Pass in file name as command line argument
        File inFile = new File("test.txt");

        //Open scanner to scan in the file and create Array List
        try (Scanner scan = new Scanner(new FileInputStream(inFile))) 
        {
            ArrayList<String> list = new ArrayList<>();


        //Create while loop to read in sentences of the file
            while(scan.hasNextLine())
            {
                String line = scan.nextLine();
                list.add(line);
            }

           int i;
            System.out.println("Input Sentences: ");
            for(i = 0; i<inFile.length(); i++)
            {
                System.out.println(i + ":");
            } 

        }


}
}

2 个答案:

答案 0 :(得分:1)

您没有将内容写入输出。做这样的事情:

 for(i = 0; i<list.size(); i++)
 {
     System.out.println(i + ":" + list.get(i));
 } 

答案 1 :(得分:0)

我猜你试图显示arraylist中的内容,所以将for循环更改为:

       for(i = 0; i<list.size(); i++)
        {
            System.out.println(i + " : " + list.get(i));
        }