我想做的是在此现有代码上添加一个stop函数。我以为如果将String输入放到如果要键入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);

}
}

最佳答案

您的代码中存在一个基本的Java错误。

您不能使用==运算符比较字符串。

仅适用于数字(例如float,int,double等)

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

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


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

10-04 12:22
查看更多