gpt4 book ai didi

java - 在当前时间停止秒表

转载 作者:行者123 更新时间:2023-12-01 15:00:57 27 4
gpt4 key购买 nike

我想做的是在这个已经存在的代码上添加一个停止函数。我认为如果我将一个字符串输入放入其中,如果我键入 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 是一个比较字符串的字符串函数

关于java - 在当前时间停止秒表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13657999/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com