Passing Variables between methods?

前端 未结 5 1809
情书的邮戳
情书的邮戳 2021-01-17 00:10

So im trying to write a simple java program for college and I\'m a complete newbie at this java stuff. I keep getting an error when I compile, \"error - could not find symbo

相关标签:
5条回答
  • 2021-01-17 00:43

    You can add the variables making them static .

        public class Order {
    
        static String clubcard;
        static double clubcard_discount;
       static  double special_discount;
      static   double balance; 
      static   double final_balance; 
      static   int apples;
       static  int oranges;
       static  int apples_cost;
       static  int oranges_cost;
    
     public static void main (String[] args) { ...
    

    Try this and let us know.

    0 讨论(0)
  • 2021-01-17 00:45

    You aren't passing the variables, that's the problem. You declared them in main. However, if you declare them as static variables before the main method, that will work.

    0 讨论(0)
  • 2021-01-17 00:54

    You have declared all your variables as local variables inside the main method, so they aren't in scope outside main. To have them accessible to other methods, you can do one of the following:

    • pass them to the methods as parameters
    • declare them as static class variables outside any methods, but inside the class.
    0 讨论(0)
  • 2021-01-17 00:57

    variables declared inside any method are for that method only(local scope). Either declare those methods at class level or pass them as arguments from main(as per use case, if methods being called from main).

    0 讨论(0)
  • 2021-01-17 00:59

    The variables you are passing are visible only inside main. The function printReceipt() is unable to see the variables because they are out of its scope of visibility.

    Here you have few options you can try and the program will work:

    • Declare the variables as the data members of the public class Order rather than keeping them as members of the main() function (best option).

      public class Order{
          static String clubcard;
          static double clubcard_discount;
          static double special_discount;
          static double balance; 
          static double final_balance; 
          static int apples;
          static int oranges;
          static int apples_cost;
          static int oranges_cost;
      
      //main() and other functions...
      
      }
      

    OR

    • Pass the data members as arguments to the PrintReceipt() function (though this may make you function a bit messy).

      public static void printReceipt(int apples, int oranges, .... .... ){

         //...defining your function 
      

      }

    Hope this helps!

    0 讨论(0)
提交回复
热议问题