0

作为家庭作业的一部分,我需要一个程序来比较使用牛顿法和 Math.sqrt 求平方根所需的时间,并实现一个在输入字符时停止程序的方法。如您所见,我创建了方法'stop 来执行此操作,但我不知道如何将其放入 main 方法中。我试图创建一个 if 语句,在输入字符“s”时调用该方法,但这会导致程序停止,直到输入一个字符。我的计划是将 if 语句放在两个 for 循环中(大多数情况下都会运行),如果没有输入任何字符,则忽略 if 语句,但我不确定如何实现这一点。我不确定此时该怎么做,所以任何帮助将不胜感激。感谢:D

public class Compare
{

   private final long start;

   public Stopwatch()
   { start = System.currentTimeMillis(); }
   public double elapsedTime()
   {
      long now = System.currentTimeMillis();
      return (now - start) / 1000.0;
   }
   public void stop()
   {
      System.out.println("The Stopwatch program has been halted");
      System.exit(0);

   }

   public static void main(String[] args)
   {

      double s = 0;


      int N = Integer.parseInt(args[0]);

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


      System.out.println(totalNewton/totalMath);
      System.out.println(timeNewton/timeMath);

   }
}
4

2 回答 2

0

我建议您继续阅读有关 java 中的线程的内容。

没有这个,你就无法完成你想做的事情。祝你好运!

于 2013-07-15T01:54:21.540 回答
0

主要方法是静态方法。你只能在其中调用静态方法,或者创建可以做事的对象。从我的角度来看,你有两个选择:

  1. 创建 Compare 类的对象并调用方法(在 main() 内部)

    Compare obj = new Compare();
    obj.stop();
    
  2. 使 stop() 方法成为静态方法(从类本身而不是从对象调用它):

    public class Compare {
        public static void stop() {
            System.out.println("The Stopwatch program has been halted");
            System.exit(0);
        }
    }
    
    public static void main(String[] args) {
    // Processing here...
    
    // Here you want to stop the program
    Compare.stop();
    }
    
于 2013-07-15T01:55:31.723 回答