Page 1 of 2 12 LastLast
Results 1 to 20 of 24
Like Tree1Likes

Thread: Completely over-thinking my class structure - second eyes, please?

  1. #1
    mallorz is offline Member
    Join Date
    Jan 2014
    Posts
    84
    Rep Power
    0

    Default Completely over-thinking my class structure - second eyes, please?

    First set of code creates an Object of the Car class. The second part of the code is the Car class itself. I don't believe I am approaching this correctly as I am not seeing the data pass through.

    I could use a second set of eyes. I've been staring at this program for far too long.

    Thank you in advance.

    Java Code:
    			Car car = new Car(customer);  // Create reference to customer for Car class
    			car.discount = car.getDiscount(customer.age);
    			car.type = car.getCar(customer.age);
    			car.rate = car.getRate(car.type);
    			car.price = car.calcCost(car.rate);
    			car.lengthOfRental = view.getDays();
    Java Code:
    	// CAR CLASS
    	class Car { 
    		
    		// Variables
    		private String type, lengthOfRental;
    		private boolean discount;
    		private double rate, price; 
    		
    		// INNER METHOD TO GET CAR TYPE BASED ON CUSTOMER AGE
    		public Car(Customer customer) {	
    			type = setCar(customer.age);	// Call to getCar method
    			discount = setDiscount(customer.age);	// Call to getDiscount method
    			rate = setRate(type);
    			price = calcCost(rate); 
    			lengthOfRental = view.getDays();
    		}
    		
    	
    		// INNER METHOD TO CHECK FOR DISCOUNT
    		public boolean setDiscount(String val){
    			
    			int age = Integer.parseInt(val);
    			boolean discount;
    			
    			if (age > 54 || age < 80)
    				discount = true;
    			else
    				discount = false;
    			
    			return discount;
    		}
    		
    		
    		// INNER METHOD TO GET RATE / DAY FOR CAR 
    		public double setRate(String type){
    			
    			if (type == "Economy Car")
    				rate = 50.00;
    			else
    				rate = 75.00;
    			
    			return rate;
    		}
    		
    		
    		// INNER METHOD TO CALCULATE COST
    		public double calcCost(double rate) {	
    			
    			if (discount == true)
    				price = Integer.parseInt(view.getDays()) * rate - 10.00;	// $10 discount applied
    			else
    				price = Integer.parseInt(view.getDays()) * rate;
    			
    			price = price * 5.5; // Add tax
    			
    			return price;
    		}	
    		
    		
    		// INNER METHOD TO DETERMINE CAR
    		public String setCar(String val) {
    			
    			int age = Integer.parseInt(val);
    			
    			if (age >= 25 || age <= 35)
    				return "Economy Car";
    			else 
    				return "Deluxe Car"; 
    		}
    		
    	} // End of Car class

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,771
    Rep Power
    5

    Default Re: Completely over-thinking my class structure - second eyes, please?

    You need to rethink how you are using the Car class. It makes no sense pass fields of a Car reference to methods of the same reference of Car.

    Java Code:
    Car car = new Car(customer);  // Create reference to customer for Car class
    // Actually, you are creating a reference to a Car class based on a specific customer.
    
    car.discount = car.getDiscount(customer.age); // why pass a parameter, you already calculated the discount when you 
                                                                    // passed in the customer class in the constructor.
    car.type = car.getCar(customer.age);
    car.rate = car.getRate(car.type);
    car.price = car.calcCost(car.rate);
    car.lengthOfRental = view.getDays();
    Once you instantiate a reference of car based on a customer, that should be sufficient to set all the fields based on that customer.

    So then you can do something like this:
    Java Code:
    String type  = car.getType();
    double rate = car.getRate();
    And you need to include your getter methods
    e.g.
    Java Code:
    public String getType() {
       return type;
    }
    Finally, since you are only using the set methods internally, you should make them private. Otherwise, someone could use the car set methods to change the state of the car class. I don't think you want that.

    Regards,
    Jim
    Last edited by jim829; 02-11-2014 at 03:08 AM.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  3. #3
    mallorz is offline Member
    Join Date
    Jan 2014
    Posts
    84
    Rep Power
    0

    Default Re: Completely over-thinking my class structure - second eyes, please?

    Jim,

    I really appreciate your reply. I had something like that earlier but still couldn't seem to put the pieces together. I am sure it is something small and stupid too.

  4. #4
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,771
    Rep Power
    5

    Default Re: Completely over-thinking my class structure - second eyes, please?

    Oh. And one more thing I didn't catch first time through. Setters almost always have a void return type. They don't typically return anything. Getters must have a return type since they must return something as the name implies.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  5. #5
    mallorz is offline Member
    Join Date
    Jan 2014
    Posts
    84
    Rep Power
    0

    Default Re: Completely over-thinking my class structure - second eyes, please?

    This is far from correct yet. So you say I don't need all of that redundancy, which I would agree with however am still stuck on syntax.

    Corrected this ...
    Java Code:
    			Car car = new Car(customer);  // Create reference to customer for Car class
    			car.discount = car.getDiscount();
    			car.type = car.getType();
    			car.rate = car.getRate();
    			car.price = car.getPrice();
    			car.lengthOfRental = view.getDays();
    To try to reflect (what will be the end result) of this ...
    Java Code:
    // CAR CLASS
    	class Car { 
    		
    		// Variables
    		private String type, lengthOfRental;
    		private boolean discount;
    		private double rate, price; 
    		
    		public String getType() {
    			return type;
    		}
    		
    		public String getDays() {
    			return lengthOfRental;
    		}
    		
    		public boolean getDiscount() {
    			return discount;
    		}
    		
    		public double getRate() {
    			return rate;
    		}
    		
    		public double getPrice() {
    			return price;
    		}
    		
    		// INNER METHOD TO GET CAR TYPE BASED ON CUSTOMER AGE
    		public Car(Customer customer) {	
    			type = car.getCar(customer.age);	// Call to getCar method
    			discount = car.getDiscount(customer.age);	// Call to getDiscount method
    			rate = car.getRate(type);
    			price = car.calcCost(rate); 
    			lengthOfRental = car.getDays();
    		}
    		
    	
    		// INNER METHOD TO CHECK FOR DISCOUNT
    		public boolean getDiscount(String customer.age){
    			
    			int age = Integer.parseInt(val);
    			boolean discount;
    			
    			if (age > 54 || age < 80)
    				discount = true;
    			else
    				discount = false;
    			
    			return discount;
    		}
    		
    		
    		// INNER METHOD TO GET RATE / DAY FOR CAR 
    		public double getRate(String type){
    			
    			if (type == "Economy Car")
    				rate = 50.00;
    			else
    				rate = 75.00;
    			
    			return rate;
    		}
    		
    		
    		// INNER METHOD TO CALCULATE COST
    		public double getPrice(double rate) {	
    			
    			if (discount == true)
    				price = Integer.parseInt(view.getDays()) * rate - 10.00;	// $10 discount applied
    			else
    				price = Integer.parseInt(view.getDays()) * rate;
    			
    			price = price * 5.5; // Add tax
    			
    			return price;
    		}	
    		
    		
    		// INNER METHOD TO DETERMINE CAR
    		public String getType(String val) {
    			
    			int age = Integer.parseInt(val);
    			
    			if (age >= 25 || age <= 35)
    				return "Economy Car";
    			else 
    				return "Deluxe Car"; 
    		}
    		
    		
    		// INNER METHOD TO GET LENGTH OF STAY
    		public String getDays() {
    			lengthOfRental = view.getDays();
    			return lengthOfRental;
    		}
    		
    	} // End of Car class
    I believe the code in the public car (customer ....) constructor is (obviously) wrong. Also, the last method for getDays() receives an error because another method exists with that name above -- as do the others, however they do not get an error.

    I could do this so easily in C#. I realize the concept is the same, but I am having difficulties with Java.

  6. #6
    mallorz is offline Member
    Join Date
    Jan 2014
    Posts
    84
    Rep Power
    0

    Default Re: Completely over-thinking my class structure - second eyes, please?

    Oh. And one more thing I didn't catch first time through. Setters almost always have a void return type. They don't typically return anything. Getters must have a return type since they must return something as the name implies.

    Regards,
    Jim

    Ahhh. Yup. Do you think I should change all of my end methods to set..()? And then maybe in the public Car(customer) reflect that? Something like ...

    type = setType();

    Would that reflect into the getType() as well?

    I really do apologize for the basic questions here, I feel like a tool.

  7. #7
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,771
    Rep Power
    5

    Default Re: Completely over-thinking my class structure - second eyes, please?

    Nope, you still don't quite have it. Here is a small class called Circle and it takes a diameter as an argument in the constructor.

    Java Code:
    public class Ball {
       private int diameter;
       public Ball(int diameter) {
           this.diameter = diameter;
       }
        
       public double getArea() {
          return Math.PI * Math.PI*diameter/2.;
       }
     
       public double getCircumference() {
           return Math.PI*diameter;
        }
    }
    And you also do stuff like this.

    Java Code:
    Car car = new Car(customer);
    car.type = car.getType();
    That is like doing the following:
    Java Code:
    int n = 2;
    n = n;
    There is no point because n was already equal to n.

    Regards,
    Jim
    Last edited by jim829; 02-11-2014 at 02:55 PM.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  8. #8
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,771
    Rep Power
    5

    Default Re: Completely over-thinking my class structure - second eyes, please?

    Yes. Change all your set methods to a void type and don't return anything. Change all your get methods to return a specific type. And like you did earlier, it is a good idea to go ahead and compute the return types in the set method. Since they won't change there is no need to recompute them every time someone wants to retrieve them. Later on, you will find that you may have reason to do the computing or conversion in the get method.

    And your class is an example of an immutable class, like the String class. Once its created you can't change the state (as long as you make your setters and instance fields private). You can only retrieve state.

    Regards,
    Jim
    Last edited by jim829; 02-11-2014 at 03:35 AM.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  9. #9
    mallorz is offline Member
    Join Date
    Jan 2014
    Posts
    84
    Rep Power
    0

    Default Re: Completely over-thinking my class structure - second eyes, please?

    (has not changed)
    Java Code:
    			Car car = new Car(customer);  // Create reference to customer for Car class
    			car.discount = car.getDiscount();
    			car.type = car.getType();
    			car.rate = car.getRate();
    			car.price = car.getPrice();
    			car.lengthOfRental = view.getDays();

    (has changed)
    Java Code:
    	// CAR CLASS
    	class Car { 
    		
    		// Variables
    		private String type, lengthOfRental;
    		private boolean discount;
    		private double rate, price; 
    		
    		public String getType() {	// Get type
    			return type;
    		}
    		
    		public String getDays() {	// Get length of rental
    			return lengthOfRental;
    		}
    		
    		public boolean getDiscount() {	// Get discount value 
    			return discount;
    		}
    		
    		public double getRate() {	// Get cars rate/day
    			return rate;
    		}
    		
    		public double getPrice() {	// Get total due
    			return price;
    		}
    		
    		public Car(Customer customer) {	
    			setType(customer.age);	// Call to getCar method
    			setDiscount(customer.age);	// Call to getDiscount method
    			setRate(type);
    			setPrice(rate); 
    			setDays();
    		}
    		
    	
    		// DISCOUNT SETTER INNER METHOD 
    		public void setDiscount(String val){
    			
    			int age = Integer.parseInt(val);
    			boolean discount = false;
    			
    			if (age > 54 || age < 80)
    				discount = true;
    		}
    		
    		
    		// RATE SETTER INNER METHOD 
    		public void setRate(String type){
    			
    			if (type == "Economy Car")
    				rate = 50.00;
    			else
    				rate = 75.00;
    		}
    		
    		
    		// PRICE SETTER INNER METHOD 
    		public void setPrice(double rate) {	
    			
    			if (discount == true)
    				price = Integer.parseInt(view.getDays()) * rate - 10.00;	// $10 discount applied
    			else
    				price = Integer.parseInt(view.getDays()) * rate;
    			
    			price = price * 5.5; // Add tax
    		}	
    		
    		
    		// TYPE SETTER INNER METHOD 
    		public void setType(String val) {
    			
    			int age = Integer.parseInt(val);
    			
    			if (age >= 25 || age <= 35)
    				type = "Economy Car";
    			else 
    				type = "Deluxe Car"; 
    		}
    		
    		
    		// DAYS SETTER INNER METHOD 
    		public void setDays() {
    			lengthOfRental = view.getDays();
    		}
    		
    	} // End of Car class
    This seems much closer although values are still not being passed through.

  10. #10
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,771
    Rep Power
    5

    Default Re: Completely over-thinking my class structure - second eyes, please?

    I see a couple of problems.

    First, use equals, not == to compare strings.

    Java Code:
    if (a.equals("foo")) {
    // do something
    }
    And this

    Java Code:
    if (n > 6 || n < 20) {
       return true;  // always returns true;
    }
    return false;

    because if all values are either less than 20 or greater than 6 then its true. They do not both have to be true. If you want to constrain a range of values use &&, not ||.

    On the other hand,

    Java Code:
    if (n < 6 && n > 20) {
     return true;
    }
    return false;
    Always returns false (nothing can be both < 6 and > 20 at the same time.


    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  11. #11
    mallorz is offline Member
    Join Date
    Jan 2014
    Posts
    84
    Rep Power
    0

    Default Re: Completely over-thinking my class structure - second eyes, please?

    Jim,

    I really appreciate all of your input. I have made the changes as well as a couple of simple syntax changes but it is still a no-go. I sincerely apologize here, but I am lost at this point.

    I know the values are not getting assigned correctly to the Car class because they do not display on my output window. I suppose I'll start poking along there .... I told myself I was going to finish this before I went to bed tonight.

    EDIT: One other weird thing, the following says 'discount' is not used. Not my main concern at the moment however, I just want to get the class assignments figured out.

    Java Code:
    		// DISCOUNT SETTER INNER METHOD 
    		public void setDiscount(String ageIn){
    			
    			int age = Integer.parseInt(ageIn);
    			boolean discount;
    			
    			if (age > 54 && age < 80)
    				discount = true;
    			else
    				discount = false;
    		}
    ** Before this gets pointed out - yes I fixed the math in the method to calculate the price. **
    Last edited by mallorz; 02-11-2014 at 04:12 AM.

  12. #12
    mallorz is offline Member
    Join Date
    Jan 2014
    Posts
    84
    Rep Power
    0

    Default Re: Completely over-thinking my class structure - second eyes, please?

    I have to go to bed - I am fried and have a long day at work tomorrow. If anyone has words of wisdom, please share. I'll be back at this tomorrow night and hopefully wrapping it up, however I'll likely require a bit more assistance to do so.

  13. #13
    mallorz is offline Member
    Join Date
    Jan 2014
    Posts
    84
    Rep Power
    0

    Default Re: Completely over-thinking my class structure - second eyes, please?

    At work so I cannot test this, but here is what I am thinking.

    When I first create a car object, I pass in the customer object as well. Therefore, I would imagine the public car(Customer) constructor is ran first, calling the set() methods listed. I would then imagine that assigning the class data to the get() methods would be adequate, but it seems they are not.

    I was thinking about this driving in today ... didn't realize that is how I had it already set up until this very moment, which is sad because I thought I was getting somewhere.

    Any more insight as to what I am doing wrong? I really do appreciate the advice you have already provided, Jim.

    Java Code:
    Car car = new Car(customer);  // Create reference to customer for Car class
    car.discount = car.getDiscount();
    car.type = car.getType();
    car.rate = car.getRate();
    car.price = car.getPrice();
    car.lengthOfRental = view.getDays();
    
    // (down to car class)
    
        public Car(Customer customer) {
            setType(customer.age);  // Call to getCar method
            setDiscount(customer.age);  // Call to getDiscount method
            setRate(type);
            setPrice(rate);
            setDays();
        }

  14. #14
    SurfMan's Avatar
    SurfMan is online now Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    983
    Rep Power
    2

    Default Re: Completely over-thinking my class structure - second eyes, please?

    In your setDiscount(...) method, you declare "boolean discount", which at that point becomes local to the method. The field "discount" is never changed. Leave out this declaration since you did that at class level. To make sure you're dealing with the instance variable, you can use: "this.discount" so you know it's assigned to the right variable (or field so you like)
    Java Code:
    public void setDiscount(String ageIn){
         
        int age = Integer.parseInt(ageIn);
        boolean discount; <----------- This one causes problems
         
        if (age > 54 && age < 80)
            discount = true;
        else
            discount = false;
    }
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  15. #15
    mallorz is offline Member
    Join Date
    Jan 2014
    Posts
    84
    Rep Power
    0

    Default Re: Completely over-thinking my class structure - second eyes, please?

    Quote Originally Posted by SurfMan View Post
    In your setDiscount(...) method, you declare "boolean discount", which at that point becomes local to the method. The field "discount" is never changed. Leave out this declaration since you did that at class level. To make sure you're dealing with the instance variable, you can use: "this.discount" so you know it's assigned to the right variable (or field so you like)

    Good catch. Thank you very much, SurfMan. I'll change it as soon as I get home. It will not solve the whole thing however it is definitely an issue!

    The price is getting passed through as it displays on my message display after the program is ran. I suspect the discount will work after this correction as well. However I have never seen values for type, days, or rate go through.

    Do you see anything relative to those? Refer to post #9 for the code, keeping in mind that I have made the suggestions from Jim in #10.

  16. #16
    mallorz is offline Member
    Join Date
    Jan 2014
    Posts
    84
    Rep Power
    0

    Default Re: Completely over-thinking my class structure - second eyes, please?

    I got it without making any other changes to the Car class besides the ones already mentioned above. I ended up changing my message call from this:

    Java Code:
    			String receipt = "Thank you, " + fullName + ". Your " + provider + " card ending in " +
    					ccnSubstring + " has been charged $" + car.price + ". \n\nSummary of purchase: " +
    					car.type + " at $" + car.rate + " a day for " + car.lengthOfRental + " day(s)." + discountMsg;
    						
    			view.displayMessage(receipt);	// Call method to display receipt
    			view.displayMessage("'The Car Shop' appreciates your business. See you again soon!");

    To this:
    Java Code:
    						summary = "PURCHASE SUMMARY: " + car.type + " at $" + car.rate + " a day for " + car.lengthOfRental + " day(s)." + discountMsg;
    
    			String receipt = "Thank you, " + fullName + ". Your " + provider + " card ending in " +
    					ccnSubstring + " has been charged $" + car.price + ". \n\n" + summary;
    						
    			view.displayMessage(receipt);	// Call method to display receipt
    In copying the code over just now I noticed that I didn't have a closing </html>, think that could have caused it? I removed them when I added the summary string because I noticed that they didn't do anything. It was something like this ...

    Java Code:
     ..."<html><b>Summary of Purchase: </b> .............
    (forgot </html>)


    Anyway - thank you both for all of your help. I know I've said it multiple times already but I am really appreciative.

  17. #17
    SurfMan's Avatar
    SurfMan is online now Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    983
    Rep Power
    2

    Default Re: Completely over-thinking my class structure - second eyes, please?

    You should make it a habit of using setters to set values instead of assigning directly to the fields.
    Java Code:
    car.price = 10;
    vs
    car.setPrice(10);
    That way the logic in setPrice() will always be run.
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  18. #18
    mallorz is offline Member
    Join Date
    Jan 2014
    Posts
    84
    Rep Power
    0

    Default Re: Completely over-thinking my class structure - second eyes, please?

    Are you saying that within the class or when setting the property outside the class? Basically, call the set() method instead of get()? Wouldn't that make one irrelevant/inoperable? I guess I don't exactly understand what you are suggesting.

  19. #19
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,771
    Rep Power
    5

    Default Re: Completely over-thinking my class structure - second eyes, please?

    When you set a value, use a setter instead of accessing the field directly. When you want to retrieve the value use a getter. There are lots of reasons for doing it but the basic concept is, it preserves encapsulation and keeps the details of the implementation away from the user. It is especially important to use setters/getters when passing mutable objects because you don't want to just store or retrieve the object itself but a copy of the object. Otherwise, the user will have alterable access to the internal state of your class which can lead to disaster.



    Regards,
    Jim
    Last edited by jim829; 02-13-2014 at 03:50 PM.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  20. #20
    SurfMan's Avatar
    SurfMan is online now Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    983
    Rep Power
    2

    Default Re: Completely over-thinking my class structure - second eyes, please?

    Quote Originally Posted by mallorz View Post
    Are you saying that within the class or when setting the property outside the class? Basically, call the set() method instead of get()? Wouldn't that make one irrelevant/inoperable? I guess I don't exactly understand what you are suggesting.
    I want you to tell me what the output is of this small program:

    Total 1: = ????
    Total 2: = ????

    You can copy/paste this if you want to test it. Most important is to think about what's happening here.

    Java Code:
    public class GetSetTest {
    
        private double price;
        private double discount;
    
        public static void main(String[] args) {
            GetSetTest gst = new GetSetTest();
            
            //Access members directly
            gst.discount = 0.1;
            gst.price = 10;
            System.out.println("Total 1: " + gst.price);
    
            //Access members via getters/setters
            gst.setDiscount(0.1);
            gst.setPrice(10);
            System.out.println("Total 2: " + gst.getPrice());
        }
    
        public double getDiscount() {
            return discount;
        }
    
        public void setDiscount(double discount) {
            this.discount = discount;
        }
    
        public double getPrice() {
            return price* ( 1 - discount);
        }
    
        public void setPrice(int price) {
            this.price = price;
        }
    
    }
    gimbal2 likes this.
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

Page 1 of 2 12 LastLast

Similar Threads

  1. Replies: 5
    Last Post: 01-16-2013, 04:32 PM
  2. Soon to graduated, thinking about freelance work
    By knightwriter in forum Jobs Discussion
    Replies: 4
    Last Post: 02-23-2012, 04:38 PM
  3. How to create class from a C structure
    By jcardozo in forum New To Java
    Replies: 8
    Last Post: 12-06-2008, 10:47 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
  •