CodingForums.com

CodingForums.com (http://www.codingforums.com/index.php)
-   Java and JSP (http://www.codingforums.com/forumdisplay.php?f=54)
-   -   Need help passing variable to another class (http://www.codingforums.com/showthread.php?t=283336)

CodyJava 12-01-2012 03:20 AM

Need help passing variable to another class
 
I'm trying to call the variable r from another class, but I'm having trouble making it.

Code:

public class Circle {
   
    final double PI = 3.14159;
    CircleTester temp = new CircleTester();
    double radius = temp.gettemprad();  //this is where i was gonna call a method but I was having trouble making one in my other class
   
    Circle(double newradius){
        newradius = radius;
    }
    Circle(){
        radius = 0.0;
    }
    void setRadius(double inputradius){
        radius = inputradius;
    }
    double getRadius(){
        return radius;
    }
   
    double getArea(){
      return PI * radius * radius;
    }
   
  double getDiameter(){
      return radius * 2;
    }
  double getCircumference(){
      return 2 * PI * radius;
  }
}


Code:

import java.util.Scanner;
public class CircleTester {
    public static void main(String [] args){
      double r;
      Circle c = new Circle();
        Scanner scan = new Scanner(System.in);
       
        System.out.println("What is the radius of the circle");
       
        r = scan.nextDouble();
       
        //after I got r to the other class i was going to call the methods below
               
        System.out.println("The circle's area is "+c.getArea());
       
        System.out.println("The circle's diameter is "+c.getDiameter());
       
        System.out.println("The circumference is "+c.getCircumference());
   
    }
   
}


Basically I want the user input (r) to go to the other class so I can get different measurements from it and then return those values back to the original class using System.out.print. Thanks.

Fou-Lu 12-03-2012 04:10 PM

Since the datatype is primitive, you cannot pass it around and change it. Only objects work via object pointer references in java (and only with mutable object types).
You can pass it to the circle's setRadius method to set the value in the class instance of Circle. Changing it within circle will not modify it in the main, for that you would need to retrieve the value again from the getRadius method (or whatever you are fetching).


All times are GMT +1. The time now is 08:50 AM.

Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.