Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 24 of 24

Thread: Working with methods and constructors

  1. #1
    Member ashl7's Avatar
    Join Date
    Mar 2013
    Posts
    32
    My Mood
    Mellow
    Thanks
    24
    Thanked 0 Times in 0 Posts

    Default Working with methods and constructors

    Hi, although by now I know enough about making methods and constructors, they're definition...I don't know why I have problem with this exercise of my teacher...now I don't want anyone to write the code, I'm just asking for some advice to find out what I'm doing wrong

    here's the problem:

    Make a class Rational to provide at least following methods and constructors:

    Rational b1= new Rational (2,7);
    Rational b2= new Rational (3,6);
    Rational b3=b1.add(b2);

    now, so far I made a class named Rational, with a constructor that takes two arguments, for numerator and denominator...but a constructor can't return anything, while in the example above(provided by the teacher), by calling the constructor, we made a Rational object with value 2/7!
    how is that possible? cuz when I printout b1 or b2, it doesn't give me the value 2/7 or 3/6, rather something like Rational@5c09036e
    I know I can make a method that makes rational number, but according to this example, we have to make that object by calling the constructor!

    I hope someone figures out where I'm making mistake lol, I'm not sure if the things I'm saying even make sense! or maybe I have not understood the problem correctly, in any ways, any help would be appreciated....


  2. #2
    Member
    Join Date
    May 2013
    Posts
    33
    Thanks
    0
    Thanked 8 Times in 8 Posts

    Default Re: Working with methods and constructors

    Rational@5c09036e type and hashcode. You need to override the toString() method to print it out in the format you would like it in. As far as the rest of your question. I have no idea, it'd probably help to include the literal instructions. If you were to have it wrong, then you would be explaining it incorrectly.

  3. #3
    Member ashl7's Avatar
    Join Date
    Mar 2013
    Posts
    32
    My Mood
    Mellow
    Thanks
    24
    Thanked 0 Times in 0 Posts

    Default Re: Working with methods and constructors

    um I know why it's not a value, cuz it's a reference variable! that's not what my question is about, I'm more asking for a solution to get a rational number by calling a constructor Rational!
    I have written this:

    public class Rational {
     
     
    	    private int num;
    	    private int den;
     
     
     
    	    public Rational(int numerator, int denominator){
     
    	        num = numerator;
    	        den = denominator;
     
    	        if(den==0){
    	            System.out.println("The second argument(denominator) can not be zero");
    	              }
     
    	    	  }

    but this constructor definitely doesn't give me(return) a rational number so I could use it with methods such as add()! (as the example in the first post wants me to do)...and if I want to add a return statement, it won't be a constructor anymore! I can make a method that divides num by den and return a rational number...but then it won't be what the question wants me to do!

    here's the whole question:
    Make a class Rational to provide at least following methods and constructors:

    Rational b1= new Rational (2,7);
    Rational b2= new Rational (3,6);
    Rational b3=b1.add(b2);

    // also sub,mult,divide methods

    Other than four operations you should provide methods that you think is useful for user of your class.

  4. #4
    Junior Member
    Join Date
    May 2013
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    I think you aren't supposed to use a traditional add in your add method but rather manipulate the numerator and denominator of both to add them. Does this make sense?

  5. #5
    Junior Member
    Join Date
    May 2013
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    Also, I'm not sure if the fraction has to be simplified because if it doesn't adding them is fairly simple. If it does need to be simplified, it is still pretty easy but will take more code.

  6. #6
    Senile Half-Wit Freaky Chris's Avatar
    Join Date
    Mar 2009
    Location
    Wales, Bangor & England, Warwickshire
    Posts
    820
    My Mood
    Cynical
    Thanks
    7
    Thanked 104 Times in 90 Posts

    Default Re: Working with methods and constructors

    If you have an object X and call the constructor of object X it creates a new instance of object X and returns it to you. You can call methods on this object such as add and subtract if you implement this.

    Look at this example:

    public class JPFExample1 {
     
        private String theString;
     
        public JPFExample1(String myString) {
            theString = myString;
        }
     
        public void printMyString() {
            System.out.println(theString);
        }
     
        public void printHisString(JPFExample1 ex) {
            ex.printMyString();
        }
     
        public static void main(String[] args) {
            JPFExample1 example1 = new JPFExample1("Hello World!");
            JPFExample1 example2 = new JPFExample1("Goodbye cruel world!");
     
            example1.printMyString();
            example1.printHisString(example2);
        }
    }

    Chris
    chris[at]javaprogrammingforums[dot]com

    Prifysgol Bangor University, North Wales

  7. The Following User Says Thank You to Freaky Chris For This Useful Post:

    ashl7 (May 11th, 2013)

  8. #7
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 262 Times in 231 Posts

    Default Re: Working with methods and constructors

    Quote Originally Posted by ashl7 View Post
    Rational b1= new Rational (2,7);
    Rational b2= new Rational (3,6);
    Rational b3=b1.add(b2);
    ...
    while in the example above(provided by the teacher), by calling the constructor, we made a Rational object with value 2/7!
    how is that possible?
    No value was given from a constructor though. Rational b3 = b1.add(b2); The final result is that b3 is given a value, but the actual work is done by the method call to the existing b1. b1.add(b2) means there is a method named add that takes a Rational object, and returns a Rational object. The hint is that the returned object will be a new one with the value of b1 added to b2.

  9. The Following User Says Thank You to jps For This Useful Post:

    ashl7 (May 11th, 2013)

  10. #8
    Member ashl7's Avatar
    Join Date
    Mar 2013
    Posts
    32
    My Mood
    Mellow
    Thanks
    24
    Thanked 0 Times in 0 Posts

    Default Re: Working with methods and constructors

    Hi...been a while, but I was working on my code, and learned some new stuff!!
    I've wrote this code so far:

    public class Rational extends Number implements Comparable<Rational>{
     
     
    	    private long numerator;
    	    private long denominator ;
     
     
    	    public Rational(){
    	    	numerator = 0;
    	    	denominator = 1;
    	    }
     
     
     
    	        // method for finding the greatest common divisor of numerator and denominator
    	        private long gcd(long n, long d){
    	    	long n1 = Math.abs(n);
    	    	long n2 = Math.abs(d);
    	    	long gcd = 1;
    	    	for (int k = 1; k<=n1 && k<=n2; k++){
    	    		if(n1%k==0 && n2%k==0){
    	    			gcd = k;
    	    		}
    	    	}
     
    	    	return gcd;
    	    		}
     
    	       public Rational(long num,long den){
     
    	    	    long gcd = gcd(num,den);
    	    	    numerator = ((denominator>0) ? 1: -1)*num/gcd;
    		        denominator = Math.abs(den)/gcd;
     
     
    		        if(den==0){
    		            System.out.println("The second argument(denominator) can not be zero");
    		            }
     
    	       }
     
    	 	   public long getNum(){
    	 	    	return numerator;
    	 	    }
     
    	 	    public long getDen(){
    	 	    	return denominator;
    	 	    }
     
    	 	    public Rational add(Rational r2){
     
    	 	    	long n = numerator* r2.getDen();
    	 	    	long d = r2.getNum()*denominator;
    	 	    	long c = denominator* r2.getDen();
    	 	    	long v = n+d;
     
    	 	    	return new Rational(v,c);
    	 	    }
     
    	 	    public String toString(){
    	 	    	if(denominator == 1){
    	 	    		return numerator+"";
    	 	    	}
    	 	    	else {
    	 	    		return numerator+"/"+denominator;
    	 	    	}
    	 	    }
     
     
    	 	    }

    in my IDE, it wants me to change my class Rational to abstract!!! why is that?!
    and when I change that, I get a new error, on my add method above, for the line: return new Rational(v,c);
    can anyone please guide me?what am I doing wrong here?!
    and the funny thing is, if I don't add abstract to the declaration of my Rational class, then test the class in a main method, it will work just fine!!! so I don't know why Eclipse says I should add abstract to it!

  11. #9
    Senior Member PhHein's Avatar
    Join Date
    Mar 2013
    Location
    Germany
    Posts
    563
    My Mood
    Sleepy
    Thanks
    9
    Thanked 82 Times in 76 Posts

    Default Re: Working with methods and constructors

    You're extending Number, which is abstract. So you have to implement it's methods. You also forgot to implement Comparable.

  12. The Following User Says Thank You to PhHein For This Useful Post:

    ashl7 (May 23rd, 2013)

  13. #10
    Member ashl7's Avatar
    Join Date
    Mar 2013
    Posts
    32
    My Mood
    Mellow
    Thanks
    24
    Thanked 0 Times in 0 Posts

    Default Re: Working with methods and constructors

    hmmm, tnx
    I'm not finished with this one yet! I will add those methods later, but it won't give me a compile error, or run error later if I don't add them right?
    also, I made this method for comparing two rational numbers:
    public void compareRational(Rational r1, Rational r2){
    	 	    	double x = r1.doubleValue();
    	 	    	double y = r2.doubleValue();
    	 	    	if (x > y)
    	 	    		System.out.println(r1 + "is greater than" + r2);
    	 	    	else if (x == y)
    	 	    		System.out.println(r1 + "is equal to" + r2);
    	 	    	else
    	 	    		System.out.println(r2 + "is greater than" + r1);
    	 	    }

    but when I want to call this method from an outside main class(but in the same package) it says : The method compareRational(Rational, Rational) is undefined for the type Test.
    why is that?
    I don't want to call my compareRational method in another class like this:
    Rational r1 = new Rational(3,5)
    Rational r2 = new Rational(1,5)
    r1.compareRational(r2)

    I like to make a method so I could call it like this:
    Rational r1 = new Rational(3,5)
    Rational r2 = new Rational(1,5)
    compareRational(r1,r2)

    basic, but would really appreciate your help

  14. #11
    Senior Member PhHein's Avatar
    Join Date
    Mar 2013
    Location
    Germany
    Posts
    563
    My Mood
    Sleepy
    Thanks
    9
    Thanked 82 Times in 76 Posts

    Default Re: Working with methods and constructors

    That is not an implementation pof the Comparable interface! Have a look at the method name and signature.

  15. #12
    Member ashl7's Avatar
    Join Date
    Mar 2013
    Posts
    32
    My Mood
    Mellow
    Thanks
    24
    Thanked 0 Times in 0 Posts

    Default Re: Working with methods and constructors

    no wasn't trying to implement Comparable interface...I deleted that part from my program....just want to make a regular method to compare two rationals!

  16. #13
    Senior Member PhHein's Avatar
    Join Date
    Mar 2013
    Location
    Germany
    Posts
    563
    My Mood
    Sleepy
    Thanks
    9
    Thanked 82 Times in 76 Posts

    Default Re: Working with methods and constructors

    The method compareRational(Rational, Rational) is undefined for the type Test.
    You have to imploement it in Test if you insist on calling it that way. Another option is to make it public static and call it with:
    Rational.compareRational(r1, r2);

  17. The Following User Says Thank You to PhHein For This Useful Post:

    ashl7 (May 24th, 2013)

  18. #14
    Member ashl7's Avatar
    Join Date
    Mar 2013
    Posts
    32
    My Mood
    Mellow
    Thanks
    24
    Thanked 0 Times in 0 Posts

    Default Re: Working with methods and constructors

    now why does it have to be "public static" and not just public?

  19. #15
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 262 Times in 231 Posts

    Default Re: Working with methods and constructors

    MyClass myClassObject = new MyClass();
    myClassObject.accessMyClassMethod();
    vs
    MyClassName.accessMyStaticClassMethod();
    Making a method static gives access to the method without creating an object of the class.

  20. The Following User Says Thank You to jps For This Useful Post:

    ashl7 (May 24th, 2013)

  21. #16
    Member ashl7's Avatar
    Join Date
    Mar 2013
    Posts
    32
    My Mood
    Mellow
    Thanks
    24
    Thanked 0 Times in 0 Posts

    Default Re: Working with methods and constructors

    hmm, thanks much...got it!

  22. #17
    Member ashl7's Avatar
    Join Date
    Mar 2013
    Posts
    32
    My Mood
    Mellow
    Thanks
    24
    Thanked 0 Times in 0 Posts

    Default Re: Working with methods and constructors

    I guess I need your help again!
    this is the code for my Rational class that I asked in the first post, which is perfectly fine

    public class Rational{
     
     
    	    private long numerator;
    	    private long denominator ;
     
     
    	    public Rational(){
    	    	numerator = 0;
    	    	denominator = 1;
    	    }
     
     
    	        // a method for finding the greatest common divisor of numerator and denominator
    	        private long gcd(long n, long d){
     
    	        long n1 = Math.abs(n);
    	    	long n2 = Math.abs(d);
    	    	long gcd=1;
    	    	for (int k = 1; k<=n1 && k<=n2; k++){
    	    		if(n1%k==0 && n2%k==0){
    	    			gcd = k;
    	    		}
    	    	}
    	    	 	return gcd;
    	    		}
     
     
    	       public Rational(long num,long den){
     
    	    	    long gcd = gcd(num,den);
    	    	    if (den > 0){
    	    	    	numerator = num/gcd;
    	    	    }
    	    	    else {
    	    	    	numerator = -num/gcd;
    	    	    }
    		        denominator = Math.abs(den)/gcd;
     
     
    		        if(den==0){
    		            System.out.println("The second argument(denominator) can not be zero");
    		            }
     
    	       }
     
     
    	       public long getNum(){
    	 	    	return numerator;
    	 	    }
    	 	    public long getDen(){
    	 	    	return denominator;
    	 	    }
     
     
    	 	    // making the add method(a/b + c/d = (ad+bc)/bd )
    	 	    public Rational add(Rational r2){
     
    	 	    	long n = numerator* r2.getDen();
    	 	    	long d = r2.getNum()*denominator;
    	 	    	long c = denominator* r2.getDen();
    	 	    	long v = n+d;
     
    	 	    	Rational q = new Rational(v,c);
    	 	    	return q;
    	 	    }
     
    	 	    // making the multiply method(a/b * c/d = ac/cd)
    	 	    public Rational multiply(Rational r2){
    	 	    	long n = numerator*r2.getNum();
    	 	    	long d = denominator*r2.getDen();
     
    	 	    	return new Rational(n,d);
    	 	    }
     
    	 	    // making the subtract method (a/b - c/d = (ad-cb)/bd)
    	 	    public Rational subtract(Rational r2){
    	 	    	long n = numerator*r2.getDen() - r2.getNum()*denominator;
    	 	    	long d = denominator*r2.getDen();
     
    	 	    	return new Rational(n,d);
    	 	    }
     
    	 	    //Making the divide method ( a/b / c/d = ad / cb )
    	 	    public Rational divide(Rational r2){
    	 	    	long n = numerator*r2.getDen();
    	 	    	long d = denominator*r2.getNum();
     
    	 	    	return new Rational(n,d);
    	 	    }
     
     
    	 	    public String toString(){
    	 	    	if(denominator == 1){
    	 	    		return numerator+"";
    	 	    	}
    	 	    	else {
    	 	    		return numerator+"/"+denominator;
    	 	    	}
    	 	    }
     
    	 	    // getting the double value of a rational number
    	 	    public double doubleValue(){
    	 	    	return numerator * 1.0 / denominator;
    	 	    }
     
    	 	    //Comparing two rational numbers
    	 	    public static void compareRational(Rational r1, Rational r2){
    	 	    	double x = r1.doubleValue();
    	 	    	double y = r2.doubleValue();
    	 	    	if (x > y)
    	 	    		System.out.println(r1 + " is greater than " + r2);
    	 	    	else if (x == y)
    	 	    		System.out.println(r1 + " is equal to " + r2);
    	 	    	else
    	 	    		System.out.println(r2 + " is greater than " + r1);
    	 	    }
     
     
    	 }

    now I made an arrays of Rational, size ten, like this:
    		Rational a[]
            a = new Rational[10];
     
     
            for(int i=0; i < a.length; i++){
                Random x = new Random();         
                int num,den;
                den = 1 + x.nextInt(9);
                num= 1 + x.nextInt(den);
     
                Rational arr1 = new Rational(num,den);
                a[i] = arr1;
    	}

    my question is, how can I show the content of my array in a jTextArea?
    I know the method, jtextareaObject.setText().....but it doesn't work for an array...also, do I need to change each Rational Number to String too? and if yes, how?! we use Integer.toString method and etc. for numbers, but for a class that I defined(Rational) how can I do that?

    I don't even have an idea of how to do it for one element of array : a1jTextArea.setText(a[1]); (which gives an error)
    thanks guys.

  23. #18
    Member angstrem's Avatar
    Join Date
    Mar 2013
    Location
    Ukraine
    Posts
    200
    My Mood
    Happy
    Thanks
    9
    Thanked 31 Times in 29 Posts

    Default Re: Working with methods and constructors

    You have toString method in your Rational class. Hence, you can roughly the same way as you act with ints. The only difference is that you invoke toString on the corresponding instance, not the whole class.

  24. #19
    Member ashl7's Avatar
    Join Date
    Mar 2013
    Posts
    32
    My Mood
    Mellow
    Thanks
    24
    Thanked 0 Times in 0 Posts

    Default Re: Working with methods and constructors

    tnx, but didn't quite get that: you mean like this: a1jTextArea.setText(a[1].toString);
    any idea about the other questions?

  25. #20
    Member angstrem's Avatar
    Join Date
    Mar 2013
    Location
    Ukraine
    Posts
    200
    My Mood
    Happy
    Thanks
    9
    Thanked 31 Times in 29 Posts

    Default Re: Working with methods and constructors

    Yes, exactly.
    By other questions you mean how to display array at the textField? Well, there's a useful class called java.util.Arrays, if you search over it, you'll find some static methods to convert arrays to string. Or you can write your own method if their format of output is insufficient for you.

  26. The Following User Says Thank You to angstrem For This Useful Post:

    ashl7 (May 26th, 2013)

  27. #21
    Member ashl7's Avatar
    Join Date
    Mar 2013
    Posts
    32
    My Mood
    Mellow
    Thanks
    24
    Thanked 0 Times in 0 Posts

    Default Re: Working with methods and constructors

    yeah
    but I'm looking for a way to display all the elements of the array on JTextField
    like this:
    a1jTextArea.setText(a[1].toString + " " + a[2].toString+ " " +.........a[10].toString)
    which doesn't work!

  28. #22
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 262 Times in 231 Posts

    Default Re: Working with methods and constructors

    What do you mean "doesn't work"?
    Do you get the wrong output? Does it even compile still?
    Explain what it does do and what it should do.
    Also it may be time to post the newest version of the code you are working with so we all see the same thing.

  29. #23
    Member ashl7's Avatar
    Join Date
    Mar 2013
    Posts
    32
    My Mood
    Mellow
    Thanks
    24
    Thanked 0 Times in 0 Posts

    Default Re: Working with methods and constructors

    Hey actually it did work out...sorry the first time I tested it my program had problem in another part that I didn't notice...but now I figured out what the problem was, it works just fine
    thanks a lot guys

    a1jTextArea.setText(a[0].toString()+"\n"+a[1].toString()+"\n"+a[2].toString()+"\n"+a[3].toString()
                        +"\n"+a[4].toString()+"\n"+a[5].toString()+"\n"+a[6].toString()+"\n"+a[7].toString()
                        +"\n"+a[8].toString()+"\n"+a[9].toString());


    --- Update ---

    sweet day
    one last question
    how can I sort out the Rational numbers in the array?!
    I know about the method Arrays.sort, but it doesn't work for a Rational array of rational numbers as element...I can convert the Rational array to a double array, and then sort it out, but I want to display the sorted array of Rational numbers on a JTextArea...so I should change doubles to Rationals, which I don't know how....anybody have a better idea about sorting out a rational array?

  30. #24
    Member angstrem's Avatar
    Join Date
    Mar 2013
    Location
    Ukraine
    Posts
    200
    My Mood
    Happy
    Thanks
    9
    Thanked 31 Times in 29 Posts

    Default Re: Working with methods and constructors

    Everything can be sorted. Even aliens coming from random directions. The reason is that you can define, who is smaller and who is grater.

  31. The Following User Says Thank You to angstrem For This Useful Post:

    ashl7 (May 27th, 2013)

Similar Threads

  1. [SOLVED] Working with Methods
    By JBtheIV in forum What's Wrong With My Code?
    Replies: 13
    Last Post: May 9th, 2013, 08:28 AM
  2. Help with methods and constructors please!
    By Xeenix in forum What's Wrong With My Code?
    Replies: 1
    Last Post: April 8th, 2013, 09:43 PM
  3. [SOLVED] Overloading constructors(Multiple Constructors)
    By chronoz13 in forum Java Theory & Questions
    Replies: 2
    Last Post: May 11th, 2011, 12:55 PM
  4. Write methods and constructors from Javadocs
    By smashX in forum What's Wrong With My Code?
    Replies: 3
    Last Post: April 20th, 2011, 10:23 PM
  5. Working with Methods
    By duckman in forum Object Oriented Programming
    Replies: 3
    Last Post: November 9th, 2009, 07:27 PM