按 Java 顺序输出句子

Output sentences in order in Java

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

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 + ":");
            } 

        }


}
}

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

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

我猜你想显示数组列表中的内容,所以将 for 循环更改为:

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