【问题标题】:Scanning in file在文件中扫描
【发布时间】:2015-04-21 15:58:46
【问题描述】:

我正在尝试将以下句子作为字符串扫描到我的 Java 程序中:

The cat in the hat
The cat sat on the mat
Pigs in a blanket

然后使用whileloop 和hasNextLine()method 将其读入列表。 我的问题是我不确定如何读取它,因为它不是指定的文本文件,我必须使用args [0]

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;

public class Scan {

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

        //Opens a scanner into the file
        File file = new File( args [0] );
        try (Scanner scan = new Scanner(file))
        {
            ArrayList<String> list = new ArrayList<String>();

            while(scan.hasNextLine())
            {
                list.add(scan.nextLine());
              }
        }

}
}

【问题讨论】:

  • 你有什么问题?
  • 我想我只是在输出它时遇到问题,只是为了检查并确保我做对了?当我运行程序时,我没有得到所需的文件输出
  • @Beginner it is not a designated text file --> 您希望从哪里获得您的意见?
  • 作为命令行参数?我猜这不是我可以在 IDE @iRuth 中检查的东西?

标签: java file arraylist while-loop java.util.scanner


【解决方案1】:

如果您只是想输出列表,使用 for each 样式循环是检查是否正确的最快方法。

for (String val : list)
{
   System.out.println(val);
}

【讨论】:

  • 请再仔细阅读问题。您的回答回答了原来的问题。
【解决方案2】:

我认为您应该将现有代码替换为以下代码:

    ArrayList<String> list = new ArrayList<String>();

    Scanner scan = new Scanner(System.in);
    while (scan.hasNextLine()) {
        list.add(scan.nextLine());
    }

    scan.close();

使用System.in 而不是new File(args[0])System.in 从标准输入读取(即用键盘输入的任何内容)。这应该适用于 IDE 和命令行输入。

我希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多