首页 文章

我've been reviewing this code for hours but I'我不确定它有什么问题

提问于
浏览
-3
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:error: ';'期望的public static double fallingDistance(int s)^ QuestionFive.java:11:error:' . class'expected public static double fallingDistance(int s)^

4 回答

  • 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.
    }
    

    如果您学会正确缩进代码,那么自己“调试”这些问题要容易得多 .

  • 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]);
            }
        }
    }
    
  • 1
    System.out.println("");
    

    应该是资本s

  • 1

    你需要将一个值传递给fallDistance函数调用 .

    value = fallingDistance(7);
    

相关问题