Results 1 to 16 of 16
  1. #1
    mainy is offline Member
    Join Date
    Feb 2009
    Posts
    38
    Rep Power
    0

    Default Using an int's value in one class in a different class

    Hello,

    Im stuck with something relativly simple, but it is causing me so many problems.

    Basically, I have two classes in one package. Lets say classA has an integer called int number = 2. How do I in totally different class called classB put system.out.println(number);.

    It will bring up an error as "number" is not recognised in classB. How do I make this point to classA? I have tried to read through the java website but it is making me mighty confused.

    Thank you

  2. #2
    dswastik is offline Senior Member
    Join Date
    Dec 2008
    Location
    Kolkata
    Posts
    282
    Rep Power
    6

    Default

    You either need to create an instance of class A in the method of Class B where you wish to access the variable or your class B should inherit class A, but in either class the variable should not be private.

    e.g.

    Java Code:
    class A{
      int x=10;
    }
    
    class B{
       void show(){
            A a1=new A();
            System.out.println(a1.x);
       }
    }

    or
    Java Code:
    class A{
      int x=10;
    }
    
    class B extends A{
      void show(){
            System.out.println(x);
      }
    }

  3. #3
    mainy is offline Member
    Join Date
    Feb 2009
    Posts
    38
    Rep Power
    0

    Default

    Ok, I got that working in a small test enviroment, but when I apply it to my actual code it doesnt seem to work. Any ideas?

    This is in one class, say class A
    Java Code:
      
    public class ClassA{
        public static void main(String[] args) {
    
    String text = "40 3 2 4 2 end";
    Scanner s = new Scanner(text);
    double arg = 0;
    double tot = 0;
      
    while (s.hasNext() ) {             
    if (s.hasNextDouble()) {       
                double x = s.nextDouble();
                arg += 1;
                tot += x;
                }
    if (s.hasNext("end")){
    s.close();
    }
    This is in the other, say ClassB.
    Java Code:
    public class ClassB{
       public static void main(String[] args) {
    
            ClassA ca = new ClassA();
            System.out.println(ca.tot);
    
    }  }
    I get an error saying "cannot resolve method println" and "cannot resolve symbol tot". I have no idea what is wrong.

  4. #4
    MK12's Avatar
    MK12 is offline Senior Member
    Join Date
    Jan 2009
    Posts
    185
    Rep Power
    6

    Default

    Its because you declared tot in a local variable inside the main method, not as field. Try declaring outside any methods.
    -MK12
    Tell me if you want a cool Java logo avatar like mine and I'll make you one.

  5. #5
    mainy is offline Member
    Join Date
    Feb 2009
    Posts
    38
    Rep Power
    0

    Default

    Sorry to be a pain, I should really read up on my foundation java before tackling more indepth stuff. This is my first Object Oreintated language and I jumped in the deep end.

    I need the main method otherwise for some reason, my scanner script won't work. How do I apply the tot variable outside of any "methods?"

    Sorry.. I don't really understand the Java lingo at the moment, heh ^^ You have to spell it out for me even simpler.

  6. #6
    MK12's Avatar
    MK12 is offline Senior Member
    Join Date
    Jan 2009
    Posts
    185
    Rep Power
    6

    Default

    like this:
    Java Code:
    class Example {
         [COLOR="orange"]private[/COLOR] double inaccessablefieldbesidesthisclass = 7;
         [COLOR="Orange"]public[/COLOR] double getField() {
              return inaccessablefieldbesidesthisclass;
         }
         public static void main(String[] args) {
              double inaccessablelocalvariablebesidesthismethod = 10;
         }
    }
    That shows local variables and fields. Note that the field is private, so it can only be used in the class, but then I provided a public accessor method which returns the field. You could just make the field public, but this way is better.
    -MK12
    Tell me if you want a cool Java logo avatar like mine and I'll make you one.

  7. #7
    mainy is offline Member
    Join Date
    Feb 2009
    Posts
    38
    Rep Power
    0

    Default

    lol, I am so confused right now. I have also read several java tutorials on the web about classes and in my BIG JAVA book by Cay Horstman. I just dont understand any of this.

    I know public class contains data and methods. I know a class can be instantiated by other other classes. I also know the different between public/private ect. I just don't know why it cant be simple to just take a value in a variable from one class and put it in another.

    I tried
    Java Code:
    public double getField(){
    return tot;
    }
    But i still got errors with the tot not being recognised. It would help if I knew what public double getField() did, just ive been trying to read up how these "contructors" work.. . even if they are constructors.. I have no idea.

    This is getting me really stressed :( I need a break

  8. #8
    CJSLMAN's Avatar
    CJSLMAN is offline Moderator
    Join Date
    Oct 2008
    Location
    Mexico
    Posts
    1,159
    Rep Power
    7

    Default

    I thought that was going to happen... OK,the quick and dirty solution is:
    Java Code:
    public class ClassA{
    [B][COLOR="Blue"]double tot = 0;[/COLOR][/B]
        public static void main(String[] args) {
    .
    .
    .
    The above puts the tot variable within the scope of all the class. Use the code that you had before in your original class B and it should work.

    Now , what MK12 was trying to tell you was that the correct way to expose a variable (specially private type) to other classes is to use an accessor method ("accessor" comes from the word "access"). If you want to use it, you have to call the accessor method, not the variable:
    Class A:
    Java Code:
    public class ClassA{
    double tot;
         
    public double [B][COLOR="Blue"]getTotal()[/COLOR][/B] {
    return tot;
    }
    
    public static void main(String[] args) {
    .
    .
    .
    Class B:
    Java Code:
    public class ClassB{
       public static void main(String[] args) {
    
            ClassA ca = new ClassA();
            System.out.println(ca.[B][COLOR="Blue"]getTtotal()[/COLOR][/B]);
    
    }  }
    Hope this helped...

    Luck,
    CJSL
    Chris S.
    Difficult? This is Mission Impossible, not Mission Difficult. Difficult should be easy.

  9. #9
    mainy is offline Member
    Join Date
    Feb 2009
    Posts
    38
    Rep Power
    0

    Default

    Thank you for your help. I have got it working, but only to some extent.

    With the changes:

    Class A:
    Java Code:
    public class ClassA{
    
            double tot = 0;
    
    public static void main(String[] args) {
    
    String text = "40 3 2 4 2 end";
    Scanner s = new Scanner(text);
    double arg = 0;
    double tot = 0;
      
    while (s.hasNext() ) {             
    if (s.hasNextDouble()) {       
                double x = s.nextDouble();
                arg += 1;
                tot += x;
                }
    if (s.hasNext("end")){
    s.close();
    }

    Class B:
    Java Code:
    public class ClassB{
    public static void main(String[] args) {
    
            ClassA ca = new ClassA();
            System.out.println(ca.tot);
    
    }  }
    This prints out 0.0, as the value of tot is intialised as 0. How do I print out the value of tot once it has gone through the while loop?


    Edit: Just to let you know, it also does this if I use the other method suggested.

  10. #10
    CJSLMAN's Avatar
    CJSLMAN is offline Moderator
    Join Date
    Oct 2008
    Location
    Mexico
    Posts
    1,159
    Rep Power
    7

    Default

    Call class B from class A after tot has processed.

    Luck,
    CJSL
    Chris S.
    Difficult? This is Mission Impossible, not Mission Difficult. Difficult should be easy.

  11. #11
    mainy is offline Member
    Join Date
    Feb 2009
    Posts
    38
    Rep Power
    0

    Default

    How do I tell the program to do that?

    This is what I have so far:

    Java Code:
    public class ClassA{
    
       double tot;
    
             public double getTotal() {
             return tot;
            }
            
    public static void main(String[] args) {
    
    String text = "40 3 2 4 2 end";
    Scanner s = new Scanner(text);
    double arg = 0;
    
    ClassA ca = new ClassA();
     
    while (s.hasNext() ) {             
    if (s.hasNextDouble()) {       
                double x = s.nextDouble();
                arg += 1;
                ca.tot += x;
                }
    if (s.hasNext("end")){
    s.close();
    }
    I think this should work, but the problem is its ClassB that is actually executed. I think for some reason, Its pulling the value of tot without actually making ClassA do anything to it.
    Last edited by mainy; 02-18-2009 at 05:06 PM.

  12. #12
    mainy is offline Member
    Join Date
    Feb 2009
    Posts
    38
    Rep Power
    0

    Default

    hello? sorry im a pain :( I am really trying to learn this stuff.

  13. #13
    CJSLMAN's Avatar
    CJSLMAN is offline Moderator
    Join Date
    Oct 2008
    Location
    Mexico
    Posts
    1,159
    Rep Power
    7

    Default

    Sorry... but I'm working right now. I would suggest the following link and I'll try to get back to you later:
    Understanding Instance and Class Members (The Java™ Tutorials > Learning the Java Language > Classes and Objects)

    Luck,
    CJSL
    Chris S.
    Difficult? This is Mission Impossible, not Mission Difficult. Difficult should be easy.

  14. #14
    StormyWaters is offline Senior Member
    Join Date
    Feb 2009
    Posts
    305
    Rep Power
    6

    Default

    It looks like to me you are trying to run two main methods, and although this is possible, this is not what you are looking for.

    You should be able to reduce them so that there is only one, and the other should become a method.

    Try pulling out the main method of class A and making it a public method that can be called on the instance of Class A in the main method of class B

  15. #15
    mainy is offline Member
    Join Date
    Feb 2009
    Posts
    38
    Rep Power
    0

    Default

    Its ok, ive kind of given up on this project. It is due in tommorow, i did the most I could but I was stuck on a few of the questions, all of which required passing of information. Just a shame I couldn't get more marks.

    I definatly think this is an area I need to look into though, I will make it my own task to try and master it.

    Thank you for everybodys input.

  16. #16
    paul pasciak is offline Senior Member
    Join Date
    Jul 2008
    Posts
    125
    Rep Power
    0

    Default I thought I knew pain, then I read this thread.

    The request is simple:

    Demonstrate how a method in one object can
    manipulate, or at least print a value in
    another object.

    To do this I'll use three classes,

    A class named Arc, which has a launching
    point, universaly known as:

    Java Code:
    public static void main(String[] args){
      ..
    }
    and its two stooge classes, named A and B.

    The code, so far, is below. If you are working
    with Windows, you can put all three classes in
    one file, in this order, and it will compile.

    Java Code:
    public class Arc{
      public static void main(String[] args){
      }
    }
    
    
    class A{
    }
    
    
    class B{
    }
    But you want an object 'A' to print a 'number'
    in an object 'B'. So next, I'll add code for
    that:

    Java Code:
    public class Arc{
      public static void main(String[] args){
      }
    }
    
    
    class A{
      public void aPrintB(){
        System.out.println(number);
      }
    }
    
    
    class B{
      int number = 102;
    }
    NOW IT WON'T COMPILE! The compiler tells
    us class A has been given the impossible
    task of printing a value "number", which
    does not exist in its scope.

    I'll fix this by adding a constructor to
    class A. A constructor specifies how I
    want an object to be initialized, or
    'instanciated'.

    Upon instanciation I want object 'A' to
    take a reference to an object 'B', and
    to store it in a variable: "referenceToB"


    Java Code:
    public class Arc{
      public static void main(String[] args){
      }
    }
    
    
    class A{
      B referenceToB;             // B reference
    
      A(B objTypeB){              // constructor
        referenceToB = objTypeB;  // constructor
      }                           // constructor
    
      public void aPrintB(){
        System.out.println(number);
      }
    }
    
    
    class B{
      int number = 102;
    }
    ..and still the same compiler error,
    because object 'A' still does not know where
    the hey to find "number".

    I have corrected this below. Object 'A' will
    print out a value "number", specifically
    from an object of type B. This code will
    compile.

    Java Code:
    public class Arc{
      public static void main(String[] args){
      }
    }
    
    
    class A{
      B referenceToB;             // B reference
    
      A(B objTypeB){              // constructor
        referenceToB = objTypeB;  // constructor
      }                           // constructor
    
      public void aPrintB(){
        System.out.println(referenceToB.number);
      }
    }
    
    
    class B{
      int number = 102;
    }
    Now run it using the command:

    java Arc

    (Remember, "Arc" contains the entry point
    for this code, "public static void main( etc."

    You'll get absolutely no results. Look at Arc,
    it has absolutely no references to A or B!
    It has no code at all, besides the launch
    point!
    So I'll have Arc 'instanciate' an "a" and "b"
    object, and in it's main I'll have it prod
    the "a" object for output from "b".
    The following code will print the value of
    "number" when you run Arc.

    Java Code:
    public class Arc{
      B b = new B();
      A a = new A(b);
    
      public static void main(String[] args){
        Arc arc = new Arc();
        arc.a.aPrintB();
      }
    }
    
    
    class A{
      B referenceToB;             // B reference
    
      A(B objTypeB){              // constructor
        referenceToB = objTypeB;  // constructor
      }                           // constructor
    
      public void aPrintB(){
        System.out.println(referenceToB.number);
      }
    }
    
    
    class B{
      int number = 102;
    }
    Here is similar code using static values.

    Java Code:
    public class Arc{
      public static void main(String[] args){
        B b = new B();
        A a = new A(b);
        a.aPrintB();
      }
    }
    
    
    class A{
      B referenceToB;             // B reference
    
      A(B objTypeB){              // constructor
        referenceToB = objTypeB;  // constructor
      }                           // constructor
    
      public void aPrintB(){
        System.out.println(referenceToB.number);
      }
    }
    
    
    class B{
      int number = 102;
    }

Similar Threads

  1. problem calling function from class to class
    By alin_ms in forum New To Java
    Replies: 3
    Last Post: 12-19-2008, 07:35 PM
  2. Calling a method on original class from created class
    By kpedersen in forum Advanced Java
    Replies: 4
    Last Post: 08-20-2008, 12:25 AM
  3. Replies: 0
    Last Post: 05-13-2008, 06:16 AM
  4. Class Reflection: Finding super class names
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-23-2008, 08:12 PM
  5. Replies: 0
    Last Post: 04-02-2008, 07:04 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •