我一直在审查这段代码几个小时,但我不确定它有什么问题

时间:2016-04-18 23:17:58

标签: java

public class QuestionFive
{
// errors 




 public static void main (String [] args) 
   {

   double fallingDistance; // reutrn value of the method 
   final double g = 9.8;   // constant value of gravity 
   int s;                  // seconds  
   double value;           // stores our methods value 



   value = fallingDistance(); 

   system.out.println(value); 



         public static double fallingDistance(int s)
         {
            for (s = 1; s <= 10; s++)
                d = 0.5 * 9.8 * (s * s);
               return d;
         }
   }


}

QuestionFive.java:11:错误:非法开始表达    public static double fallingDistance(int s)    ^ QuestionFive.java:11:错误:非法开始表达    public static double fallingDistance(int s)           ^ QuestionFive.java:11:错误:';'预期    public static double fallingDistance(int s)                 ^ QuestionFive.java:11:错误:'。class'预期    public static double fallingDistance(int s)                                             ^

4 个答案:

答案 0 :(得分:3)

您需要将fallingDistance方法移出main方法的主体。 Java不支持直接在其他方法中定义方法。

public class QuestionFive {
  public static void main (String [] args) {
    // ...
  }  // Missing this brace.

  public static double fallingDistance(int s)
    // ...
  }

  // } // Remove this extraneous brace.
}

&#34;调试&#34;更容易如果您学会正确缩进代码,这些问题就会自行解决。

答案 1 :(得分:1)

您需要将值传递给fallDistance函数调用。

value = fallingDistance(7); 

答案 2 :(得分:1)

System.out.println("");

应该是资本s

答案 3 :(得分:0)

如上所述,您无法在main方法内部创建方法,因此您必须将方法移到main方法之外。这应该清除非法表达的开始。

但是,我不认为您可以让一个方法显式返回多个值,因为您似乎正在尝试在上面的代码中执行。你可以做的是创建一个数组,通过调用main方法中的数组索引来存储你可以调用的每个值。或者就像现在一样,您可以调用方法来打印所有值。希望这有帮助

public class Tester
{
    //these are the class variables so that you can call them
    //from any of the static methods in this class.
    public static final double gravity =  9.8; // meters/second
    public static int seconds = 0; //initial time
    public static double[] physics =  new double[10]; // declares and initializes the array to hold your values

    public static void main(String[]args)
    {
    doPhysics(); // the call for your method 

    //i represents the index value from 0-9 (based on it being a ten index array)
    for (int i = 0; i<10; i++){
        System.out.println(Tester.physics[i]);
    }
    }

    public static void doPhysics()
    {

        for (int second = Tester.seconds; second < Tester.physics.length; second++){ // Tester. is needed because the variables are static and require the class reference
        Tester.physics[second] =  0.5 * Tester.gravity * (second * second); // second doubles as the array index and the current second 
        System.out.println("second: "+ second + "  "+ Tester.physics[second]);
        }
    }
}