【问题标题】:How to run Java programs from Algorithms textbook by Robert Sedgewick?如何从 Robert Sedgewick 的算法教科书中运行 Java 程序?
【发布时间】:2019-02-04 16:26:11
【问题描述】:

对于一个新手问题,我深表歉意。我正在尝试在 Eclipse 中运行由 Robert Sedgewick 和 Kevin Wayne 编写的算法第 4 版书中给出的 Java 程序:https://algs4.cs.princeton.edu/home/

程序的输入参数有问题。

例如以下程序:

import java.util.Arrays;

public class BinarySearch
{
    public static int rank(int key, int[] a)
    { // Array must be sorted.
     int lo = 0;
        int hi = a.length - 1;
        while (lo <= hi)
        { // Key is in a[lo..hi] or not present.

          int mid = lo + (hi - lo) / 2;
            if (key < a[mid]) hi = mid - 1;
            else if (key > a[mid]) lo = mid + 1;
            else return mid;
        }
        return -1;
    }



    public static void main(String[] args)
    {

        int[] whitelist = In.readInts(args[0]);
        Arrays.sort(whitelist);
        while (!StdIn.isEmpty())
        { // Read key, print if not in whitelist.        
         int key = StdIn.readInt();
            if (rank(key, whitelist) < 0)
            StdOut.println(key);
        }    
    }
}

输入参数是:

% java BinarySearch tinyW.txt < tinyT.txt

我不知道在 Eclipse 中在哪里传递输入参数。任何帮助将不胜感激。

【问题讨论】:

  • Go to Run->Run As-> Run configuration ... 你会看到命令行参数文本框,你可以在其中添加参数
  • int key = StdIn.readInt(); 这不起作用。除非你使用lib。
  • 由于您的程序依赖于重定向,因此您必须打开一个 cmd 窗口并从命令行运行 Java。 IDE 不支持文件重定向。
  • @RealSkeptic 我在 cmd 中尝试过。但它会引发错误。命令中的“
  • 请把错误添加到您的问题中。

标签: java eclipse algorithm


【解决方案1】:

进入“运行配置...”,打开播放按钮的菜单。

您可以在参数、环境选项卡和常用选项中找到所需的内容。 实际上常见的是您需要的选项卡。

【讨论】:

  • 这对 OP 命令行中的文件重定向没有帮助。
  • 应该,见eclipse.org/mars/noteworthy/#_assigning_stdin_to_a_file 在常用选项卡上,选中“输入文件”并选择tinyT.txt
  • 我写的。我发布了主对话框,但我也写下了这个选项卡 common 正是他需要的。但总的来说,他可以在它周围找到其他所有东西。
【解决方案2】:

谢谢大家! 我解决了。显然,图书网站上提供的较新的图书馆与我的书有所不同。

我把main函数改成如下:

import java.util.Arrays;
public class BinarySearch{
public static int rank(int key, int[] a)
{ // Array must be sorted.
    int lo = 0;
    int hi = a.length - 1;
    while (lo <= hi)
    { // Key is in a[lo..hi] or not present.
        int mid = lo + (hi - lo) / 2;
        if (key < a[mid]) hi = mid - 1;
        else if (key > a[mid]) lo = mid + 1;
        else return mid;
    }
    return -1;
}

public static void main(String[] args)
{
    In i = new In(args[0]);
    In j = new In(args[1]);
    int[] whitelist = i.readAllInts();
    int[] iplist = j.readAllInts();
    Arrays.sort(whitelist);
    for (int key:iplist)
    { // Read key, print if not in whitelist.
        if (rank(key, whitelist) < 0)
        StdOut.println(key);
    }
}
}

然后通过

"tinyW.txt" "tinyT.txt"

作为@GDG612 指示的程序参数。

【讨论】:

    【解决方案3】:

    右键单击您的程序并选择Run As -&gt; Run Configurations... 然后点击(x)= Arguments选项卡并将输入传递给Program arguments下的程序

    【讨论】:

    • 文件重定向呢?
    猜你喜欢
    • 1970-01-01
    • 2016-06-29
    • 1970-01-01
    • 2010-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-15
    相关资源
    最近更新 更多