【问题标题】:intelliJ IDEA run class with command line argument带有命令行参数的 IntelliJ IDEA 运行类
【发布时间】:2018-01-08 06:29:34
【问题描述】:

我正在阅读 Sedgewick 的算法书,但我似乎无法让我的 IDE 运行他们的程序。程序启动但不会接受传递的参数。具体来说,我希望它打开我在程序参数部分设置的 tiny.txt 文件,但它只是被忽略了......

import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.StdOut;

public class Selection
{
    public static void sort(Comparable[] a)
    {  // Sort a[] into increasing order.
        int N = a.length;               // array length
        for (int i = 0; i < N; i++)
        {  // Exchange a[i] with smallest entry in a[i+1...N).
            int min = i;                 // index of minimal entr.
            for (int j = i+1; j < N; j++)
                if (less(a[j], a[min])) min = j;
            exch(a, i, min);
        } }
    // See page 245 for less(), exch(), isSorted(), and main().
    private static boolean less(Comparable v, Comparable w)
    {  return v.compareTo(w) < 0;  }

    private static void exch(Comparable[] a, int i, int j)
    {  Comparable t = a[i]; a[i] = a[j]; a[j] = t;  }

    private static void show(Comparable[] a)
    {  // Print the array, on a single line.
        for (int i = 0; i < a.length; i++)
            StdOut.print(a[i] + " ");
        StdOut.println();
    }

    public static boolean isSorted(Comparable[] a)
    {  // Test whether the array entries are in order.
        for (int i = 1; i < a.length; i++)
            if (less(a[i], a[i-1]))  return false;
        return true;
    }
    public static void main(String[ ] args)
    {  // Read strings from standard input, sort them, and print.
        String[] a = In.readStrings();
        sort(a);
        assert isSorted(a);
        show(a);
    }
}

【问题讨论】:

  • 您可以使用终端选项卡并从 IntelliJ 中的命令行运行 Java,应该具有相同的效果 :-)
  • 您没有在Selection.main 中使用args。您希望它如何注意到命令行参数?
  • @Welshboy 当我通过终端尝试时,它只会给我这个错误:192:algorithms2 errorNot$ java Selection
  • @DodgyCodeException 这是他们应该可以工作的代码,我没有改变任何东西
  • 我还注意到您没有在静态 void main 中使用 String[] 参数。您没有使用传递给 main 的数组中的任何内容。

标签: java intellij-idea command-line-arguments


【解决方案1】:

您似乎想要标准输入重定向。不幸的是,IntelliJ 不支持。

当您提供命令行参数时,所做的只是将参数中的每个单词作为字符串传递给main 方法的args 参数。然后,您可以在 main 中编写一些代码来打开该文件上的 BufferedReader。

另一种方法是打开终端窗口(或命令提示符窗口)并键入命令行java package.name.ClassName &lt; filename.ext。命令处理器或 shell 将 &lt; 字符解释为将标准输入重定向到提供的文件的请求。

【讨论】:

    【解决方案2】:

    好吧,如果您想在 mac OS Sierra 上使用 intelliJ IDEA 中的算法代码,则需要这样做:

    1,确保从他们的网站获取并运行 algs4.app

    2、使用intelliJ终端导航到.class文件所在的algorithm2/out/production/algorithms2

    3、在终端输入:$ java-algs4 选择/mistakeNot/Desktop/Java/algorithms2/tiny.txt

    【讨论】:

      猜你喜欢
      • 2014-12-11
      • 1970-01-01
      • 2022-10-04
      • 2011-01-05
      • 2020-05-12
      • 2011-08-23
      • 1970-01-01
      相关资源
      最近更新 更多