0

我想要做的是在这个已经存在的代码上添加一个停止功能。我想我可以实现一个停止功能,如果我将一个字符串输入放到哪里,如果我输入 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);

}
}
4

1 回答 1

1

您的代码中有一个基本的 java 错误。

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

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

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

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

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

于 2012-12-01T11:11:00.483 回答