Java 在当前时间停止秒表

Java 在当前时间停止秒表,java,stopwatch,Java,Stopwatch,我要做的是在这个已经存在的代码上添加一个stop函数。我想我可以实现一个停止函数,如果我把一个字符串输入到其中,如果我输入s表示停止,程序将在当前时间停止。所以当我按下s时,它的运行方式与不使用if语句时的运行方式相同 public class Stopwatch { private final long t; public Stopwatch() { t=System.currentTimeMillis(); } public double elapsedTime() {

我要做的是在这个已经存在的代码上添加一个stop函数。我想我可以实现一个停止函数,如果我把一个字符串输入到其中,如果我输入s表示停止,程序将在当前时间停止。所以当我按下s时,它的运行方式与不使用if语句时的运行方式相同

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);

}
}
公共类秒表{
私人最终长t;
公众秒表
{
t=System.currentTimeMillis();
}
公共双elapsedTime()
{
返回值(System.currentTimeMillis()-t)/1000.0;
}
公共双停车(双牛顿、双时间、双总牛顿、双总时间)
{
双时间牛顿=牛顿;
双时间数学=时间;
双总牛顿=总牛顿;
double totalMath=tottime;
标准打印项数(totalNewton/totalMath);
标准输出(时间牛顿/时间数学);
返回时间;
}
公共静态void main(字符串[]args)
{
System.out.println(“输入N:”);
int N=StdIn.readInt();
double totalMath=0.0;
秒表swMath=新秒表();
对于(int i=0;i
您的代码中有一个基本的java错误

不能将字符串与==运算符进行比较

这只适用于数字(如浮点、整数、双精度等)

在if条件中使用s.equals(“s”)

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

equals是一个比较字符串的字符串函数

“我以为我可以实现…”嗯。那个计划出了什么问题?我意识到由于程序在等待输入,它不会工作。所以,当我按下s键时,它的运行方式与不使用if语句时的运行方式相同。你确定要自己的秒表吗?外面有很多。考虑Apache Con on LangStIt实际上是一个我很难理解的任务。