【发布时间】:2012-12-01 09:09:10
【问题描述】:
我想做的是在这个已经存在的代码上添加一个停止函数。我想我可以实现一个停止功能,如果我将一个字符串输入放到哪里,如果我输入 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);
}
}
【问题讨论】:
-
“我以为我可以实现..” 嗯嗯。该计划出了什么问题?
-
我意识到由于程序正在等待输入,它无法工作。因此,当我按 s 时,它的作用与不使用 if 语句运行时相同。
-
您确定要自己的秒表吗?那里有很多。考虑 apache commons-lang
-
这实际上是一个我很难理解的作业。