Search code examples
javastopwatch

stopping a stopwatch on its current time


What I'm trying to do is add a stop function on this already existing code. I thought that I could implement a stopping function if I were to put an String input to where if I were to type s for stop, the program would stop on the current time. So when I press s, it does the same as if it were to run without the if statement

public class Stopwatch {

private final long t;

public Stopwatch()
{

    t=System.currentTimeMillis();

}

public double elapsedTime()
{

    return (System.currentTimeMillis() - t) / 1000.0;

}

public double stopping(double newton, double time, double totnewt, double tottime)
{
    double timeNewton = newton;
    double timeMath = time;
    double totalNewton = totnewt;
    double totalMath = tottime;

    StdOut.println(totalNewton/totalMath);
    StdOut.println(timeNewton/timeMath);


    return time;
}

public static void main(String[] args)
{
    System.out.println("Enter N:");
    int N = StdIn.readInt();




    double totalMath = 0.0;
    Stopwatch swMath = new Stopwatch();

    for (int i = 0; i < N; i++)
        totalMath += Math.sqrt(i);

    double timeMath = swMath.elapsedTime();

    double totalNewton = 0.0;
    Stopwatch swNewton = new Stopwatch();

    for (int i = 0; i < N; i++)
    totalNewton += Newton.sqrt(i);
    double timeNewton = swNewton.elapsedTime();


    String s = StdIn.readString();
    if (s == "s")
    {

        swMath.stopping(timeNewton, timeMath, totalNewton, totalMath);
        swNewton.stopping(timeNewton, timeMath, totalNewton, totalMath);
    }


    StdOut.println(totalNewton/totalMath);
    StdOut.println(timeNewton/timeMath);

}
}

Solution

  • There's a basic java error in your code.

    You can't compare strings with an == operator.

    That only works for numbers (eg. float, int, double etc.)

    Use s.equals("s") instead in the if condition

    if (s.equals("s"))
    {
        swMath.stopping(timeNewton, timeMath, totalNewton, totalMath);
        swNewton.stopping(timeNewton, timeMath, totalNewton, totalMath);
    }
    

    equals is a string function that compares the strings