【问题标题】:How to use .in files as input for eclipse in Google Code Jam?如何在 Google Code Jam 中使用 .in 文件作为 eclipse 的输入?
【发布时间】:2014-09-18 09:55:40
【问题描述】:

我已经寻找了很长时间的解决方案,但令人惊讶的是,似乎没有人在我之前遇到过这个问题。

Google Code Jam.in 文件的形式提供输入。我查看了解决方案以了解人们如何处理这种输入。我将解决方案复制到 eclipse 并将.in 文件作为输入,但控制台保持空白,我猜这意味着扫描仪无法将.in 文件作为正常输入读取。如何在 Eclipse 中直接从.in 文件中读取输入?

这是用于读取输入的代码(同样,直接在 .in 文件上尝试时它不起作用)。

public class A {
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        int numberOfCases = in.nextInt();

                    int next  = in.nextInt();

                    //some unimportant piece of code

            System.out.format("Case #%d: %d\n", currentCase, max(bTime, oTime));
        }
    }

我只缩短了与问题有关的部分的代码。您可以在http://www.go-hero.net/jam/11/name/theycallhimtom(在“Bot Trust”-> S 下)查看完整答案。

【问题讨论】:

  • “将 .in 文件作为输入”是什么意思?您当前的代码从标准输入读取,这将是您的控制台/键盘,除非您已将文件通过管道传输到您的程序(这不是从 eclipse 中直接向前)。您应该先打开文件,然后再从中读取。
  • 我在运行时使用 .in 文件作为 Eclipse 内部的输入 -> 运行配置 -> 参数

标签: java eclipse input file-format


【解决方案1】:

这就是我要做的......

    File file = new File("F:\\A-small-practice.in");
    File outFile = new File("F:\\A-small-practice.out");
    BufferedReader br = new BufferedReader(new FileReader(file));
    BufferedWriter bw = new BufferedWriter(new FileWriter(outFile));
    int testCases = Integer.parseInt(br.readLine());
    for(int t=1;t<=testCases;t++){
        /*
         * Your code here
         */

        bw.write("Case #" + t +": Yes I did it\n");
    }
    br.close();
    bw.close();

我在F盘下载.in文件然后访问它,将.out文件写入其中。

【讨论】:

    【解决方案2】:

    System.in 代表standard input,这意味着它通常是从键盘读取的。所以,如果你启动你的程序,然后在控制台窗口中输入整个.in 文件,它就可以工作。

    但您不想每次都键入文件,而是可以redirect 输入从.in 文件而不是键盘读取。据我所知,在 Eclipse 中没有执行此操作的选项,但您可以通过在命令行中添加 &lt; 后跟文件名来启动程序的正常命令。整个命令可能类似于:

    java -jar A.jar < A-small.in
    

    另一种选择是将输入文件的名称作为程序的参数(这就是您使用的 Eclipse 选项的用途)。这些参数可以从main 方法的args 参数访问。为此,您实际上必须告诉Scanner 使用该文件:

    Scanner in = new Scanner(new File(args[0]));
    

    另一种选择是硬编码文件名:

    Scanner in = new Scanner(new File("A-small.in"));
    

    这样做在任何类型的生产代码中都被认为是一种不好的做法,但对于编程竞赛来说可能没问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-21
      • 1970-01-01
      相关资源
      最近更新 更多