简体   繁体   中英

Java is not printing integer variables

The following code receives two file names from command line and prints the numbers in the second file that are not in the first file. I also need to print how many numbers of this kind there are. Let's say the program prints:

12
13
14

I have to change it to print in the end:

12
13
14
There are 3 numbers!

That's why I created the variable ns in the main function.

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)
    {
        In in = new In(args[0]);
        int[] whitelist = in.readAllInts();
        Arrays.sort(whitelist);

        int ns = 0;

        while (!StdIn.isEmpty())
        {
            int key = StdIn.readInt();

            if (rank(key, whitelist) == -1)
            {
                StdOut.println(key);
                ns++;
            }
        }

        System.out.println(ns);
    }
}

It compiles and I run java BinarySearch tinyW.txt < tinyT.txt . It does print

12
13
14

but it does not print the ns variable in the end as it should. Does anyone know why?

The only reason why your program won't print the ns variable is because it didn't execute that line of code.

You might have an infinite loop because "!StdIn.isEmpty()" is always true.

You can quickly check that the integer is not your problem by moving that printing code right above your while instruction.

You should set your $CLASSPATH correctly. I suggest you add to .bashrc :

#Variables
JAVA=$HOME/algs4

#Set $CLASSPATH
if [ -d $JAVA ]; then
        export CLASSPATH=.:$JAVA/stdlib.jar:$JAVA/algs4.jar
fi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM