0

I was trying out the stopwatch class in http://algs4.cs.princeton.edu/14analysis/Stopwatch.java.html . I'm using Eclipse, and here are the things I've done-

Here's the code -

public class HelloWorld {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int n = Integer.parseInt(args[0]);

        // sum of square roots of integers from 1 to n using Math.sqrt(x).
        Stopwatch timer1 = new Stopwatch();
        double sum1 = 0.0;
        for (int i = 1; i <= n; i++) {
            sum1 += Math.sqrt(i);
        }
        double time1 = timer1.elapsedTime();
        StdOut.printf("%e (%.2f seconds)\n", sum1, time1);

        // sum of square roots of integers from 1 to n using Math.pow(x, 0.5).
        Stopwatch timer2 = new Stopwatch();
        double sum2 = 0.0;
        for (int i = 1; i <= n; i++) {
            sum2 += Math.pow(i, 0.5);
        }
        double time2 = timer2.elapsedTime();
        StdOut.printf("%e (%.2f seconds)\n", sum2, time2);
    }

}

I've added external JAR stdlib to the Java buildpath

However, when I run it, I still get the error-

Error message

Could someone please help me out and tell me what I'm doing wrong?

K.Dᴀᴠɪs
  • 9,945
  • 11
  • 33
  • 43

2 Answers2

0

The problem is in the StdOut lines. That class does not exist in the JDK. Generally it is used for teaching purposes, as here.

So, to solve your class not found exception replace them like here:

public class HelloWorld {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int n = Integer.parseInt(args[0]);

        // sum of square roots of integers from 1 to n using Math.sqrt(x).
        Stopwatch timer1 = new Stopwatch();
        double sum1 = 0.0;
        for (int i = 1; i <= n; i++) {
            sum1 += Math.sqrt(i);
        }
        double time1 = timer1.elapsedTime();
        System.out.println(String.format("%e (%.2f seconds)\n", sum1, time1));

        // sum of square roots of integers from 1 to n using Math.pow(x, 0.5).
        Stopwatch timer2 = new Stopwatch();
        double sum2 = 0.0;
        for (int i = 1; i <= n; i++) {
            sum2 += Math.pow(i, 0.5);
        }
        double time2 = timer2.elapsedTime();
        System.out.println(String.format("%e (%.2f seconds)\n", sum2, time2));
    }
}

As you may notice, now there are two System.out.println.

P3trur0
  • 3,155
  • 1
  • 13
  • 27
0

It worked when I followed the steps outlined here- How to import a jar in Eclipse

Thank you everyone for your time!