0

I am trying to run a program in Algorithms (4th ed.)

package binarysearch;
import edu.princeton.cs.introcs.*;
import java.util.Arrays;

public class BinarySearch {
    public static int rank(int key, int[] a) 
    {
    int lo = 0;
    int hi = a.length - 1;
    while (lo <= hi)
    {
        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())
    {
        int key = StdIn.readInt();
        if (rank(key, whitelist) == -1)
        StdOut.println(key);
    }
    }
}

The command to run the program is

% java BinarySearch tinyW.txt < tinyT.txt

I added the textfile to the package I want to run.

enter image description here

I also added the arguments needed in the run configuration.

enter image description here

But Eclipse is telling me this error message.

enter image description here

I am not sure why Eclipse cannot open the file. I set the file permission to 777 as well manually. Any idea?

Jason Kim
  • 18,102
  • 13
  • 66
  • 105

2 Answers2

2

You're trying to redirect your input, I think. See this.

So tinyW.txt is your program argument, that's OK.
But tinyT.txt is not, you're just trying to
redirect tinyT.txt to stdin.

https://bugs.eclipse.org/bugs/show_bug.cgi?id=155411

Seems Eclipse does not support this.

I would just try running it from outside of Eclipse.

Also see this. Eclipse reading stdin (System.in) from a file

Community
  • 1
  • 1
peter.petrov
  • 38,363
  • 16
  • 94
  • 159
2

Looking at the source code of the In class, it looks like you silently swallowed an IOException.

Could not open tinyW.txt

This causes a NullPointerException down the line because the Scanner that In uses internally is not initialized.

If I had to guess, the root cause of this exception is a FileNotFoundException.

Instead of putting your file in the package of your class, put it at the root of the project directory. Eclipse usually runs your application from that directory, so all relative paths, like tinyW.txt are relative to that directory.

Once you've solved this, know that using shell redirect operators as java arguments will not have the desired effect. Eclipse is running your application a little something like this

java binarysearch.BinarySearch "tinyW.txt < tinyT.txt"

where you can obviously see that the < is inside the quotes and is therefore not handled by the shell parser.


Consider using anything other than the In class you've been provided. It's a terrible mess, swallowing exceptions and all.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724