在Java中按顺序输出句子
我目前正在尝试获取文本文件中句子顺序的输出:在Java中按顺序输出句子,java,string,file,for-loop,arraylist,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循环的某个地方 public static void main(String[] args) throws FileNotFoundException{ //Pass in file name as comm
0 : The cat in the hat
1 : The cat sat on the mat
2 : Pigs in a blanket
我将文本文件添加到ArrayList
中,目前无法显示上述输出。我知道问题出在for循环的某个地方
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 + ":");
}
}
}
}
publicstaticvoidmain(字符串[]args)抛出FileNotFoundException{
//将文件名作为命令行参数传入
File infle=新文件(“test.txt”);
//打开扫描仪扫描文件并创建阵列列表
try(Scanner scan=new Scanner(new FileInputStream(infle)))
{
ArrayList=新建ArrayList();
//创建while循环以读入文件的句子
while(scan.hasNextLine())
{
String line=scan.nextLine();
列表。添加(行);
}
int i;
System.out.println(“输入句子:”);
对于(i=0;i您没有将内容写入输出。请执行以下操作:
for(i = 0; i<list.size(); i++)
{
System.out.println(i + ":" + list.get(i));
}
for(i=0;i我猜您是在尝试显示arraylist中的内容,因此将for循环更改为:
for(i = 0; i<list.size(); i++)
{
System.out.println(i + " : " + list.get(i));
}
for(i=0;我很乐意。但是,使用两个循环并不是一个很好的方法。您可以在while循环本身中显示内容。在这种情况下,您也不需要ArrayList(除非您希望存储内容,以便以后可以重用它们)。