Just learning how to use constructors...
Hey, I'm back with some more questions. This part in the course I'm taking is quite confusing because the pages I had to read to learn about constructors literally began to talk about cats, dogs, rabbits and assorted other animals in the code and it totally threw me off so I'm hoping some of the people here could help me figure out constructors and how to work with them a little bit better.
For my current assignment I'm writing up a little program that uses a constructor and two methods that I'd call to convert between celsius and fahrenheit. I've written up most of what I think I need for the program to work but I'm confident that there are a lot of errors and mistakes in the program. I'd like if someone could look over it and maybe explain what I'm doing wrong and how it should be done etc...
Code :
import java.io.*;//tells Java input will be used
class Assignment9Question2
{
//constructor with 3 parameters to initialize the variables
Assignment9Question2(double celsiusTemp, double farenheitTemp)
{
System.out.println("Nothing here yet!");
}
public void convertToCelcius(double farenheitTempEnt)
{
//Conversion of temperature and output of the resulting infomration.'
double celsiusTemp = (5.0 / 9.0) * (farenheitTempEnt - 32);
System.out.println("");
}
public void convertToFarenheit(double celsiusTempEnt)
{
//Conversion of temperature and output of the resulting infomration.
double farenheitTemp = (9.0 / 5.0) * (celsiusTempEnt + 32);
System.out.println(""+celsiusTempEnt+" would be "+farenheitTemp+" in farenheit.");
}
}
// Test Class
class Assignment9Question1Tester
{
public static void main (String[] args) throws IOException
{
InputStreamReader inStream = new InputStreamReader (System.in);
BufferedReader userInput = new BufferedReader (inStream);
String inData;
double celsiusTempEnt = 0.0, farenheitTempEnt = 0.0; //Declares two double variables
System.out.println ("Enter a temperature in farenheit:"); //asks for user input
inData = userInput.readLine ( ); //places input into inData variable
farenheitTempEnt = Double.parseDouble(inData); //converts string to double and places into a double variable
System.out.println ("Enter a temperature in celsius:");
inData = userInput.readLine ( ); //places input into inData variable
celsiusTempEnt = Double.parseDouble(inData); //converts string to double and places into a double variable
Assignment9Question2 = new Assignment9Question2("+celsiusTempEnt+", "+farenheitTempEnt+");
}
}
There are a few things I haven't yet added into the program, I think all I forgot was the thing that calls one or the other method in the Assignment9Question2 class.
Re: Just learning how to use constructors...
Mmm, it's not clear for me what exactly are you expecting from us, but regarding constructors I can say
You can have private, default and public constructors
You can't inherit a constructor
If you have a hierarchy, the first line of the subclass constructor will call to the superclass constructor (even if you did not explicity put that code)
You can have several constructors in the same class, it's like overloading a method.
You should never put business logic in the constructors
Hope it helps you ...
Re: Just learning how to use constructors...
Well, to start you should initialize your variables before any of your methods. Otherwise, anything you make the constructor initialize won't be recognized outside of the constructor method, and therefore won't be able to be used in the other two methods. Basically, a constructors purpose is to create an object using defined set of parameters, or set variables to a predetermined value. How you learn to execute it will depend on who teaches it to you, but I find method overloading to be best. Basically, I recommend making two constructor classes; one that sets your variables to default values, in this case 0.0, and one that sets your variables to values that are passed through to the constructor, in this case your double variables. You also shouldn't name the variables passed through the same name as the variables you initialized at the top. Another thing I noticed is that in your conversion method you have the results of the equations equal to either celsiusTemp or farenheitTemp. I wouldn't recommend this, because that will overwrite the same variable values that were passed in to the constructor. Instead, you should make a third variable for the equation results, and then print out that variable instead. Basically, this is what you're aiming for:
I wrote this because I think its easier to understand constructors if you look at them head on, and because the code itself is rather simple. Read my first paragraph, and then try to determine exactly what each constructor and comment is doing in your program. Its important to understand these, because from here on they are an integral part of any program.
Re: Just learning how to use constructors...
@bankston13 please read The Problem with Spoon-feeding
I agree that sample code is a great learning tool. But there are plenty of constructor examples without writing the code that fits the project
Re: Just learning how to use constructors...
First off, thanks for removing the code jps it would count as cheating if I used it (well I think it would.)
Secondly, I re-wrote the code with a few of the tips from above in-mind and I have some more questions...
1.) Do I need to create and set the variables in both classes or just the first one for them to work throughout the entire program?
2.) I'm getting an error when I call the methods with lines 61 and 62. The error is:
Assignment9Question2Tester.java:61: convertToCelsius(double) in Assignment9Question2 cannot be applied to (java.lang.String)
The other error looks the same but for line 62. I believe the error is coming up because I more-or-less just guessed how to pass the variable with the methodCaller to the method in the first class.
Code :
import java.io.*;//tells Java input will be used
class Assignment9Question2
{
double celsiusTemp=0.0, farenheitTemp=0.0, celsiusTempEnt=0.0, farenheitTempEnt=0.0, farenheitTempFin=0.0, celsiusTempFin=0.0;
//constructor with 3 parameters to initialize the variables
Assignment9Question2(double celsiusTemp, double farenheitTemp)
{
System.out.println("Nothing in the constructor yet!");
}
public void convertToCelsius(double farenheitTempEnt)
{
//Conversion of temperature and output of the resulting infomration.'
celsiusTempFin = (5.0 / 9.0) * (farenheitTempEnt - 32);
System.out.println(""+farenheitTempEnt+" would be "+celsiusTemp+" in celsius.");
}
public void convertToFarenheit(double celsiusTempEnt)
{
//Conversion of temperature and output of the resulting infomration.
farenheitTempFin = (9.0 / 5.0) * (celsiusTempEnt + 32);
System.out.println(""+celsiusTempEnt+" would be "+farenheitTemp+" in farenheit.");
}
}
// Test Class
class Assignment9Question1Tester
{
public static void main (String[] args) throws IOException
{
double celsiusTempEnt=0.0, farenheitTempEnt=0.0;
InputStreamReader inStream = new InputStreamReader (System.in);
BufferedReader userInput = new BufferedReader (inStream);
String inData;
System.out.println ("Enter a temperature in farenheit:"); //asks for user input
inData = userInput.readLine (); //places input into inData variable
farenheitTempEnt = Double.parseDouble(inData); //converts string to double and places into a double variable
System.out.println ("Enter a temperature in celsius:");
inData = userInput.readLine (); //places input into inData variable
celsiusTempEnt = Double.parseDouble(inData); //converts string to double and places into a double variable
Assignment9Question2 methodCaller = new Assignment9Question2("+celsiusTempEnt+", "+farenheitTempEnt+");
methodCaller.convertToCelsius("+farenheitTempEnt+");
methodCaller.convertToFarenheit("+celsiusTempEnt+");
}
}
Thanks for the help so-far, I understand it at-least a bit better than I did yesterday :o
Re: Just learning how to use constructors...
Quote:
Originally Posted by
jps
@bankston13 please read
The Problem with Spoon-feeding
I agree that sample code is a great learning tool. But there are plenty of constructor examples without writing the code that fits the project
Sorry, didn't mean for it to be a solution. I guess i didn't think of using a different example.
Re: Just learning how to use constructors...
Quote:
First off, thanks for removing the code jps it would count as cheating if I used it (well I think it would.)
I can't think of a place it would be anything but...
There are better ways to word much of this, but in an attempt to keep it short:
Quote:
1.) Do I need to create and set the variables in both classes or just the first one for them to work throughout the entire program?
If I understand what you are asking, this may help.
Think of class Assignment9Question2 as a box. A container to put things in. Not just any generic container, but a specific container custom fit to your needs. Much in the way an egg crate is formed to hold multiple eggs. Or the way a soap dish is shaped to hold a bar of soap. This class is the way for you to hold a group of items.
The Assignment9Question1Tester class is a class that is more like a set of instructions that will do some action with objects of the Assignment9Question2 class. Hold thoughts on this class for a moment longer.
Think of class Assignment9Question2. The container. There are little pockets inside this container shaped like a double. In this class when you say:
double celsiusTemp=0.0, farenheitTemp=0.0, celsiusTempEnt=0.0, farenheitTempEnt=0.0, farenheitTempFin=0.0, celsiusTempFin=0.0;
you have created six places to hold a double, and put the value 0.0 in each place, inside this container. Initializing a variable when it is declared is not a bad idea, though it is not always required. So giving the value 0.0 to each double at this point is perfectly fine. (Yes this is one of the cases where it is not required as will be discussed.)
Besides the doubles, this container also has some methods. A method in a class is a set of instructions to perform some action on the data built in to the class. In this case the class seems to store a temperature, and have the ability to convert between C and F. Methods that belong in this class are methods that perform actions on data as wide as the class itself. Methods that perform actions on multiple objects of the class would go in the tester class. (this is not to be taken as a rule, just for now to make things clear think of it this way)
In the tester class when you create an object of the Assignment9Question2 class, you create a container to put things in. This is done by calling the constructor for the class. For example:
MyClassName myVariableName = new MyClassName(0.0, 32.0);
This would create a variable that holds an object of my class, and it looks like two values of type double were passed to the constructor, and should have been saved in two of the 'pockets' in the class for later use.
Here is a sample class which also represents the data structure (container) type class:
Code java:
/** FILE: Apple.java */
package forumsamples;
/**
* @author jps
* This class represents an apple...
*/
public class Apple {
/**The approximate diameter of the apple represented in inches*/
public double diameterInInches;
/**True if the apple has a worm, false otherwise*/
public boolean hasWorm;
/**True if the apple has a great taste, false otherwise*/
private boolean greatTaste;
/** Constructs an Apple object:
* @param diameterInInches The diameter of the apple measured in inches.
* @param hasWorm True if the apple has a worm in it, false otherwise.
*/
public Apple(double diameterInInches, boolean hasWorm) {
this.diameterInInches = diameterInInches;
this.hasWorm = hasWorm;
this.greatTaste = true;//of course my perfect apples have great taste!
}
/** @return True if the apple has a great taste, false otherwise. */
public boolean hasGreatTaste() {
return greatTaste;
}
/** @param greatTaste Set the great taste of the apple. */
public void setGreatTaste(boolean greatTaste) {
//this.greatTaste = greatTaste;
this.greatTaste = true;//I am a crooked salesman :P
}
}
In this sample class the constructor takes two arguments, (or parameters, or any of the other terms they have been given...) One is type double and represents the diameter of the apple in inches. The second is type boolean and is true if the apple is known to have a worm. To create an object of this class a line of code might look like the following:
Apple myAppleObjectsLongVariableName = new Apple(4.2, false);
Another, more reasonable, line of code might look like this:
Apple apple = new Apple(4.2, false);
Now that I have an object of my class, I can use the variable name to refer to that object. Some code to use this object:
Code java:
/** FILE: .AppleTest.java */
package forumsamples;
/** @author jps
* This class tests the class Apple */
public class AppleTest {
//TODO This sample class does not fully test the Apple class!
/**@param args Not used*/
public static void main(String[] args) {
//create an instance of the class to be tested..
Apple goodApple = new Apple(4.2, false);
Apple badApple = new Apple(2.4, true);
//refer to a public variable of the specific objects
if(goodApple.hasWorm) {
System.out.println("My good apple has a worm! Ewww!");
System.out.println("I'm reporting Bad Taste!");
goodApple.setGreatTaste(false);//crooked setter method will not allow this!
}
if(badApple.hasWorm) {
System.out.println("My bad apple has a worm! Ewww!");
System.out.println("I'm reporting Bad Taste!");
badApple.setGreatTaste(false);//crooked setter method will not allow this!
}
//use a class method to get the value of a private variable
System.out.println("Let's see what the report has to say now!");
if(goodApple.hasGreatTaste()) {
System.out.println("The good apple tastes great!");
}
else {
System.out.println("The apple tastes like it has a worm!");
}
if(badApple.hasGreatTaste()) {
System.out.println("The bad apple tastes great!");
}
else {
System.out.println("The apple tastes like it has a worm!");
}
//we know the apple has a worm, or at least half of one...
System.out.println("Liar! The bad apple has a worm and worms only taste great with ketchup!");
}
}
If you have any more questions don't hesitate to ask.
Re: Just learning how to use constructors...
Quote:
Originally Posted by
bankston13
Sorry, didn't mean for it to be a solution. I guess i didn't think of using a different example.
No problem. To be honest, there are many days I would rather have had some functional code to look at rather than looking up answers to questions I did not know how to ask.
I don't like removing code personally. I think the people who want to learn more, will, and people who want to cheat, will, regardless of if code is posted or not.
But by all means thanks for offering help. My kind of people.
Re: Just learning how to use constructors...
I wish you were the one who wrote the lessons for my class jps, that made a lot more sense than cats and dogs. =P
The program is starting to work properly, but there is still one thing that I can't figure out how to do. I need to send the variables 'celsiusTempEnt' and 'farenheitTempEnt' from Assignment9Question2Tester up to the constructor class without entering pre-set numbers; this is because I need to get the user to input a farenheit and celsius temperature and then create a new object which, when created, needs to send the inputted data up to the constructor.
Currently I'm trying to send the variables up with this line, I took a guess and wrote in the "+celsiusTempEnt+" and "+farenheitTempEnt+" parts since that works when using println:
Assignment9Question2 testCaller = new Assignment9Question2("+celsiusTempEnt+", "farenheitTempEnt");
Re: Just learning how to use constructors...
Post the new version of the code with each new question so we are all on the same page.
Re: Just learning how to use constructors...
Code :
import java.io.*;//tells Java input will be used
class Assignment9Question2
{
double celsiusTemp, farenheitTemp, celsiusTempEnt, farenheitTempEnt, farenheitTempFin, celsiusTempFin;
//constructor with 2 parameters to initialize the variables
Assignment9Question2(double celsiusTemp, double farenheitTemp)
{
System.out.println(""+celsiusTempEnt+" & "+farenheitTempEnt+""); // CHANGE THIS TO SOMETHING, IT IS JUST FOR TESTING NOW
}
public void convertToCelsius()
{
//Conversion of temperature and output of the resulting infomration.'
celsiusTempFin = (5.0 / 9.0) * (farenheitTempEnt - 32);
System.out.println(""+farenheitTempEnt+" would be "+celsiusTemp+" in celsius.");
}
public void convertToFarenheit()
{
//Conversion of temperature and output of the resulting infomration.
farenheitTempFin = (9.0 / 5.0) * (celsiusTempEnt + 32);
System.out.println(""+celsiusTempEnt+" would be "+farenheitTemp+" in farenheit.");
}
}
// Test Class
class Assignment9Question2Tester
{
public static void main (String[] args) throws IOException
{
double celsiusTempEnt=0.0, farenheitTempEnt=0.0;
InputStreamReader inStream = new InputStreamReader (System.in);
BufferedReader userInput = new BufferedReader (inStream);
String inData;
System.out.println ("Enter a temperature in farenheit:"); //asks for user input
inData = userInput.readLine (); //places input into inData variable
farenheitTempEnt = Double.parseDouble(inData); //converts string to double and places into a double variable
System.out.println ("Enter a temperature in celsius:");
inData = userInput.readLine (); //places input into inData variable
celsiusTempEnt = Double.parseDouble(inData); //converts string to double and places into a double variable
Assignment9Question2 testCaller = new Assignment9Question2(10.0, 15.0); //The 10 and 15 are for testing, they will be changed when I figure out this variable thing
testCaller.convertToCelsius();
testCaller.convertToFarenheit();
System.out.println(""+celsiusTempEnt+" and "+farenheitTempEnt+""); //ERASE THIS LINE, THIS IS JUST FOR TESTING
}
}
I didn't change too much but I did get it working (except for the variable thing I was talking about). There are probably a few errors in the first class but I'll work on fixing those after I figure out the variable thing.
Re: Just learning how to use constructors...
To use a variable just type the variable name in place of a value of the same type.
For example you can use a variable of type double anywhere you would have put (for example) 100.0 in the code.
Search passing variables as parameters
Re: Just learning how to use constructors...
Quote:
Originally Posted by
jps
To use a variable just type the variable name in place of a value of the same type.
For example you can use a variable of type double anywhere you would have put (for example) 100.0 in the code.
Search passing variables as parameters
Thanks, looks like everything is working as intended and I should have an easier time working with constructors and that in the next assignment.:o
Re: Just learning how to use constructors...
I am glad you got everything working.
Please see the announcements page for details on marking a thread closed and other forum info.