【问题标题】:Output sentences in order in Java在Java中按顺序输出句子
【发布时间】:2015-04-22 20:49:07
【问题描述】:

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

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

        }


}
}

【问题讨论】:

    标签: java string file for-loop arraylist


    【解决方案1】:

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

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

    【讨论】:

    • 我的荣幸。但是,使用两个循环并不是一个很好的方法。您可以在 while 循环本身中显示内容。在这种情况下,您也不需要 ArrayList(除非您想存储内容,以便以后可以重用它们)。
    【解决方案2】:

    我猜你正在尝试显示数组列表中的内容,因此将 for 循环更改为如下所示:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-05
      • 2010-09-28
      相关资源
      最近更新 更多