Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I've been trying to use getters and setters along with toString and I'm having trouble seeing what the issue is with my code. I'm not sure where the problem lies exactly.
So, am i supposed to have a main? I'm unsure if thats needed or not in this situation.
Also, is there any way i could better format the "Rectangle(x, x)" It looks kinda weird the way it is at the moment.
public class Rectangle {
// DO NOT MODIFY THE INSTANCE VARIABLES
// begin instance variables
private int width;
private int height;
// end instance variables
// TODO - write your code below this comment.
// You need to do the following:
//
// 1.) Define a constructor which takes two ints
// representing the width and height, respectively.
// The constructor should set its instance variables
// equal to these values.
//
// 2.) Define a "getter" named getWidth, which returns
// the width of the rectangle.
//
// 3.) Define a "getter" named getHeight, which returns
// the height of the rectangle.
//
// 4.) Define a "setter" named setWidth, which takes
// the new width of the rectangle and sets the
// rectangle's width to that value.
//
// 5.) Define a "setter" named setHeight, which
// takes the new height of the rectangle and sets
// the rectangle's height to that value
//
// 6.) Define a toString method, which returns
// a String representation of the rectangle.
// As an example, if the width of the rectangle is
// 3 and the height of the rectangle is 4, this should
// return the String:
//
// "Rectangle(3, 4)"
//
public Rectangle(int rectWidth, int rectHeight) {
rectWidth = width;
rectHeight = height;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public void setWidth(int rectWidth) {
width = rectWidth;
}
public void setheight(int rectHeight) {
height = rectHeight;
}
public String toString() {
return s;
}
public static void main(String[] args) {
Rectangle s = new Rectangle("Rectangle"+"("+rectWidth+",
"+rectHeight+")");
System.out.println(s);
}
}
A couple of things: your constructor was incorrect:
You need to set the instance variables for "this" object that you are creating, and you must call the constructor with the correct arguments.
ToString should be used to obtain a string representation of this particular instance of Rectangle. Try this:
public class Rectangle {
// DO NOT MODIFY THE INSTANCE VARIABLES
// begin instance variables
private int width;
private int height;
// end instance variables
// TODO - write your code below this comment.
// You need to do the following:
//
// 1.) Define a constructor which takes two ints
// representing the width and height, respectively.
// The constructor should set its instance variables
// equal to these values.
//
// 2.) Define a "getter" named getWidth, which returns
// the width of the rectangle.
//
// 3.) Define a "getter" named getHeight, which returns
// the height of the rectangle.
//
// 4.) Define a "setter" named setWidth, which takes
// the new width of the rectangle and sets the
// rectangle's width to that value.
//
// 5.) Define a "setter" named setHeight, which
// takes the new height of the rectangle and sets
// the rectangle's height to that value
//
// 6.) Define a toString method, which returns
// a String representation of the rectangle.
// As an example, if the width of the rectangle is
// 3 and the height of the rectangle is 4, this should
// return the String:
//
// "Rectangle(3, 4)"
//
public Rectangle(int rectWidth, int rectHeight) {
// "this" refers to the instance of Rectangle you are creating
// so this objects width and height are set to the values passed into the constructor...
this.width = rectWidth;
this.height = rectHeight;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public void setWidth(int rectWidth) {
width = rectWidth;
}
public void setheight(int rectHeight) {
height = rectHeight;
}
public String toString() {
// the toString returns a string representation for "this" object
return "Rectangle(" + this.width + "," + this.height + ")";
}
public static void main(String[] args) {
Rectangle s = new Rectangle(5,4);
System.out.println(s);
}
}
Related
My assignment was to create a class named MyRectangle to represent rectangles.
The required data fields are width, height, and color. Use double data type for width and height, and a String for color. Then Write a program to test the class MyRectangle. In the client program, create two MyRectangle objects. Assign a width and height to each of the two objects. Assign the first object the color red, and the second, yellow. Display all properties of both objects including their area.
I've written everything out and am getting no errors, but my output stays the same no matter what values I put in for the rectangles.
package MyRectangle;
public class MyRectangle{
private double width = 1.0;
private double height = 1.0;
private static String color = "black";
public MyRectangle(double par, double par1){
width ++;
height ++;
}
//Parameters for width, height, and color //
public MyRectangle(double widthParam, double heightParam, String colorParam){
width = widthParam;
height = heightParam;
color = colorParam;
width ++;
height ++;
}
// Accessor width //
public double getWidth(){
return width;
}
public void setWidth(double widthParam){
width = (widthParam >= 0) ? widthParam: 0;
}
// Accessor height //
public double getHeight(){
return height;
}
public void setHeight(double heightParam){
height = (heightParam >= 0) ? heightParam: 0;
}
// Accessor color //
public static String getColor(){
return color;
}
public static void setColor(String colorParam){
color = colorParam;
}
// Accessor area //
public double findArea(){
return width * height;
}
}
class MyRectangleTest {
#SuppressWarnings("static-access")
public static void main(String args[]) {
// Create triangle and set color value to red //
MyRectangle r1 = new MyRectangle(5.0, 25.0);
r1.setColor("Red");
System.out.println(r1);
System.out.println("The area of rectangle one is: " + r1.findArea());
// Create triangle and set color value to yellow //
MyRectangle r2 = new MyRectangle(3.0, 9.0);
r2.setColor("Yellow");
System.out.println(r2);
System.out.println("The area of rectangle one is: " + r2.findArea());
}
}
The constructor you are using makes no sense.
You ignore the passed rectangle dimensions, so you'll always get a 2 by 2 rectangle:
private double width = 1.0;
private double height = 1.0;
...
public MyRectangle(double par, double par1){
width ++;
height ++;
}
It should be something like :
public MyRectangle(double width, double height){
this.width = width;
this.height = height;
}
In addition, the color member shouldn't be static, unless you want all your rectangles to have the same color.
One last thing - in order for System.out.println(r1); and System.out.println(r2); to Display all properties of both objects, you must override toString():
#Override
public String toString()
{
return "width = " + width + " height = " + height + " color = " + color;
}
There are a couple of things wrong here:
The color member is static, which means in belongs to the class, instead of each instance having its own.
The (double, double) constructor doesn't store the height and the width.
Both constructors increment the height and the width, for no good reason.
Since you don't have a default constructor, the default values for the members are redundant - there's no flow where they won't be overwritten.
To sum it up, your class should be declared more or less like this:
public class MyRectangle {
private double width;
private double height;
private String color;
private static final String DEFAULT_COLOR = "black";
public MyRectangle(double width, double height) {
this (width, height, DEFAULT_COLOR);
}
public MyRectangle(double width, double height, String color) {
this.width = width;
this.height = height;
this.color = color;
}
// Rest of the required methods
}
I have been assigned the following task for an introductory java course:
You should write a class that represents a circle object and includes the following:
Private class variables that store the radius and centre coordinates of the object.
Constructors to create circle objects with nothing supplied, with just a radius value supplied and with a radius and centre coordinates supplied.
Public instance methods that allow the radius and centre coordinates to be set and retrieved (often known as set/get methods).
Public instance methods that return the circumference and area of the circle.
A public class method that tests if two circle objects overlap or not
Here is my code:
import java.lang.Math;
public class Circle {
private double xCentre, yCentre, Radius;
// constructors
public Circle() {
xCentre = 0.0;
yCentre = 0.0;
Radius = 1.0;
}
public Circle(double R) {
xCentre = 0.0;
yCentre = 0.0;
Radius = R;
}
public Circle(double x, double y, double R) {
xCentre = x;
yCentre = y;
Radius = R;
}
//getters
public double getX() {
return xCentre;
}
public double getY() {
return yCentre;
}
public double getRadius() {
return Radius;
}
//setters
public void setX(double NewX) {
xCentre = NewX;
}
public void setY(double NewY) {
yCentre = NewY;
}
public void setRadius(double NewR) {
Radius = NewR;
}
//calculate circumference and area
public double Circumference() {
return 2*Math.PI*Radius;
}
public double Area() {
return Math.PI*Radius*Radius;
}
//determine overlap
public static double Overlap(Circle c1, Circle c2) {
double xDelta = c1.getX() - c2.getX();
double yDelta = c1.getY() - c2.getY();
double separation = Math.sqrt(xDelta*xDelta + yDelta*yDelta);
double radii = c1.getRadius() + c2.getRadius();
return separation - radii;
}
}
}
and
import java.io.Console;
public class cp6 {
public static void main(String args[]){
//Set up the Console
Console myConsole = System.console();
//Declare cirlce
Circle first = new Circle(2.0,4.0,6.0);
myConsole.printf("Circumference of first circle is ", first.Circumference(), "\n");
myConsole.printf("Area of first circle is ", first.Circumference(), "/n");
first.setRadius(2);
first.setX(2);
first.setY(2);
myConsole.printf("New X of first circle is ", first.getX(), "/n");
myConsole.printf("New Y of first circle is ", first.getY(), "/n");
myConsole.printf("New Radius of first circle is ", first.getRadius(), "/n");
Circle second = new Circle(-1.0,3.0,5.0);
Circle third = new Circle(1,1,1);
if (Circle.Overlap(second, third) <= 0) {
myConsole.printf("Second and third circles overlap");
}
else {
myConsole.printf("Second and third circles do not overlap");
}
myConsole.printf("New Y of first circle is ", first.getY());
Calculate and print out distance between them using the class method
myConsole.printf("Distance between first and second is : %.5g\n", Circle.Overlap(first, second));
}
}
The second program just has to demonstrate each aspect addressed in the brief I pasted at the top and I've only a rough idea of how to do this so if what I'm doing seems stupid to any of you please offer suggestions of what else I can do.
Your problem is that you're using the Console.printf() method incorrectly.
The first parameter to this method should be a format, and it has to have placeholders inside it for the other parameters. Read up on it in The Java Platform documentation. In fact, you should familiarize yourself with the Java platform documentation. You need to use it often to make sure you're calling methods correctly or what methods are available in a given class.
So, your printout lines should actually have been:
myConsole.printf("Circumference of first circle is %.2f%n", first.Circumference());
myConsole.printf("Area of first circle is %.2f%n", first.Area());
...etc.
The format %.2f means "The corresponding parameter is a floating-point number. Display it with a precision of 2 digits after the decimal point". The %n replaces your "\n" - the whole "template" of the print should be just in the format string. And in this type of format, one should use %n instead of \n.
I'm not sure why you opted for using the system console rather than the usual System.out.println(). If you choose to go with System.out, there is also a printf() method there that works exactly as Console.printf() - the first parameter is a format, the others are embedded in it.
One last comment: there are conventions when writing Java code:
Indent your code properly
Class names' first letter is always uppercase.
Non-constant fields and local variable names' first letter is always lowercase.
Method names also start with a lowercase letter.
I am new to java and trying to understand the use of this keyword in java.As per documentation if instance and local variables have same name then local variables mask the instance variables.We use this keyword so that instance variable may not be masked by local variable.Below is the program i was writing to understand the use of this key work but even after use of this keyword instance variable is still getting masked.
class Box{
int height=5;
int length=10;
int breadth=15;
int CalcVol(){
int vol = height*breadth*length;
return vol;
}
Box(int height, int length,int breadth){
this.height = height;
length = length;
breadth = breadth;
System.out.println("height is " + height);
}
}
class MyBox{
public static void main(String args[]){
Box mybox1 = new Box(10, 20, 30);
int vol=mybox1.CalcVol();
System.out.println("volume is" + vol);
}
}
What i am thinking is that variable "height" printed in Box constructor should print 5 ie value of instance variable but its printing 10 ie the value passed as parameter.Please help me on this.
You need to add this before every field you want to access :
Box(int height, int length,int breadth){
// ...and move this statement to the beginning, otherwise this.height gets overriden.
System.out.println("height is " + this.height);
this.height = height;
this.length = length;
this.breadth = breadth;
}
Otherwise, length = length and breadth = breadth have no effect.
It is a name collision problem.
Within the constructor Box are the parameters height, length, and breadth. Those are also names of three fields within Box.
In Java, one considers member variables and block variables to be "closer" than field variables. As such, if you use the exact same name for both (as you have done), the assignment
height = height
will assign the parameter height to the exact same value it held (effectively a noop).
To avoid this issue, you will specify which height you are assigning.
this.height = height;
which is shorthand for "this class's height" or "the field height". When there is no name collision, the compiler will assume you meant the field variable; because there is nothing else with that name in the block.
As an aside, this is a really good reason to learn how to use the final keyword. Final means that the variable can be assigned once, and only once. It prevents it from being reassigned in situations you probably would never want.
For example
public Box(final int height, final int width, final int breadth) {
would then throw a compliation error upon
height = height;
because you are reassigning the value of height. Such techniques are very valuable when writing code, because they prevent you from writing something you think is a field assignment, when you really wrote a parameter assignment.
For your class:
class Box{
int height=5;
int length=10;
int breadth=15;
Box(int height, int length,int breadth){
this.height = height;
length = length;
breadth = breadth;
System.out.println("height is " + height);
}
}
When you construct Box, the following is happening:
Instance variable height is being set to the constructor parameter height
Constructor parameter length is being set to itself (not changing instance variable length)
Constructor parameter breadth is being set to itself (not changing instance variable breadth).
What you probably want to do in the constructor is set your instance variables with the values passed into the constructor like this:
Box(int height, int length,int breadth){
this.height = height;
this.length = length;
this.breadth = breadth;
}
You are performing an assignment here, which will make this.height take on the value of the parameter height.
this.height = height;
If you want to print the original value of this.height, put the print above the assignment and print with this.height.
System.out.println("height was " + this.height);
More completely, your constructor should look like this. Note that you need to prefix with the this keyword on every access to any instance variable that is shadowed by a local variable.
Box(int height, int length,int breadth){
System.out.println("height was " + this.height);
this.height = height;
this.length = length;
this.breadth = breadth;
}
Rather than not understanding the usage of the this keyboard in Java, I think OP isn't understanding object oriented programming in general, seeing how he's trying to print out "5" when the value has already changed. The this keyword becomes a lot less confusing once you understand that concept.
Suppose you have your class Box, and it only has one value, height:
class Box {
// This is a instance variable, that is, each new instance of Box
// has a different height variable even if they are all equal to 5
// initially. It's a different variable in memory.
int height = 5;
// Here's our constructor that sets this instance's value of height
Box(int height){
this.height = height;
}
When you make a new Box, you are making a new Box Object - for each object the height will initially start at 5, but you are changing the height of that instance of Box in your constructor.
Box box1 = new Box(10); // Height was originally 5, but changed to 10 in the constructor
Box box2 = new Box(20); // Height was originally 5, but changed to 20 in the constructor
Box box3 = new Box(30); // Height was originally 5, but changed to 30 in the constructor
When you get to the following line of code in your original program:
System.out.println("height is " + height);
It doesn't matter if it was this.height or height, it will never return 5. You already changed the value of the instance's height in the constructor.
So then. How do we print out a default height of 5? You can't. Not with the same variable name. You have to define constants in the class (like final int HEIGHT = 5) which represent the default values for that class, or use another constructor that doesn't set those values.
class Box{
int height=5;
int length=10;
int breadth=15;
int CalcVol(){
int vol = height*breadth*length;
return vol;
}
Box() {
System.out.println("height is " + height);
}
Box(int height, int length,int breadth) {
this.height = height;
this.length = length;
this.breadth = breadth;
System.out.println("height is " + height);
}
}
class MyBox{
public static void main(String args[]){
Box mybox1 = new Box(10, 20, 30); // this will never print 5, and always 10
Box mybox2 = new Box(); // this will always print 5
}
}
However, if you move the print statement above the assignment and used this.height, like Maxim Bernard did, then it will print out 5, since we didn't change the value yet.
Box(int height, int length,int breadth) {
System.out.println("height is " + this.height); // this will print out 5
this.height = height;
this.length = length;
this.breadth = breadth;
}
If this is really confusing, rather than trying to understand Java's this keyword I suggest just reading a few articles on OOP. You'll understand then that this simply means the current instance of a class.
Can someone please tell me what's wrong with this simple program? I'm getting output as "0".
package myConst;
public class Doconstructor
{
int length,width;
Doconstructor(int x, int y)
{
int area;
area = length * width;
System.out.println("area ="+area);
}
}
class work
{
public static void main(String args[])
{
Doconstructor d1 = new Doconstructor(10, 15);
}
}
Doconstructor d1 = new Doconstructor(10, 15);
// you are assigning values for x and y
But
Doconstructor (int x,int y)
{
int area; // you are never use x and y values for calculation
area = length *width; // so area remain 0 since current length and width is 0
System.out.println("area ="+area);
}
You need to change your code as follows.
Doconstructor (int x,int y)
{
int area;
this.length=x;
this.width=y;
area = length *width;
System.out.println("area ="+area);
}
Edit like this:-
package myConst;
public class Doconstructor
{
int length,width;
Doconstructor(int x, int y)
{
int area;
this.length=x;//Using this for current object
this.width=y;//Using this for current object
area = length * width;
System.out.println("area ="+area);
}
}
class work
{
public static void main(String args[])
{
Doconstructor d1 = new Doconstructor(10, 15);
}
}
Your output will be:
area =150
Must read this :
http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
You are not setting the values of length and width and by default they are both 0. You might have to do this:
Doconstructor(int x, int y){
int area;
area = x * y;
length = x;
width = y;
System.out.println("Area = "+area);
}
You're not using the variable values you pass to the constructor in it but rather the length and width values that have been initialized to 0. You want area = x * y; instead.
The length and width fields are implicitly initialized to 0. Multiply them and you get 0.
I think what you want is
length = y ;
width = x ;
int area = length * width ;
System.out.println("area ="+area);
You have this:
public class Doconstructor {
int length,width;
Doconstructor (int x,int y)
{
int area;
area = length *width;
System.out.println("area ="+area);
}
}
At no point do you set length or width equal to anything. Their initial values are 0 and your program is doing precisely what you told it to do. area = length * width = 0 * 0 = 0.
You also are not doing anything with the x or y that you passed to the constructor, but this probably was not your intention. When writing programs, you basically need to clearly instruct the computer to do what you want to do. It's not going to guess what you want. If you ignore x and y, and don't assign any values to length or width, then that is precisely what will happen and you cannot be surprised when you see the results you see.
you are writing int length,width at class level so length and width are set to 0 as default.
After that in the constructor you are not setting any values to length and width so you are the values for length and width are 0.Hence area is also 0
Please check this link for list of default values
Constructors are used to create objects and to set the attributes. You are not setting the attributes in your constructor. Here is how your constructor should look like.
Doconstructor(int x, int y){
length = x;
width = y;
}
Secondly you are mixing the logic of a constructor and a method. You are doing the calculation of area, which seems to be a perfect fit for another method in your class. so better move that logic in a separate method:
public int calculateArea() {
int area;
area = x * y;
return area;
}
Finally create an object using constructor to set the attributes length and width. And then call calculateArea method to do the business logic of calculating area.
public static void main(String args[]){
Doconstructor d1 = new Doconstructor(10, 15); // create object and set length & width
d1.calculateArea();
}
you are not assigning the value of x and y to the variables width and length. The default value of width and length are (int) 0. Thats why you are getting the output (0*0=0). First assign the values to the variables or use "area=x*y;" .
I'm having trouble with fixing this error. Can someone please help? My prompt and the code is posted below.
Write a super class encapsulating a rectangle. A rectangle has two attributes representing the width and the height of the rectangle. It has methods returning the perimeter and the area of the rectangle. This class has a subclass, encapsulating a parallelepiped, or box. A parallelepiped has a rectangle as its base, and another attribute, its length. It has two methods that calculate and return its area and volume. You also need to include a client class to test these two classes.
public class Rectangle1
{
protected double width;
protected double height;
public Rectangle1(double width, double height){
this.width = width;
this.height = height;
}
public double getWidth(){
return width;
}
public void setWidth(double width) {
this.width = width;
}
public double getHeight(){
return height;
}
public void setHeight(double height){
this.height = height;
}
public double getArea(){
return width * height;
}
public double getPerimeter(){
return 2 * (width + height);
}
}
public class Box extends Rectangle1 {
protected double length;
public Box(double length){
this.length = length;
}
public double getLength(){
return length;
}
public void setLength(double length){
this.length = length;
}
public double getVolume(){
return width * height * length;
}
}
public class TestRectangle {
public static void main(String[] args) {
Rectangle1 rectangle = new Rectangle1(2,4);
Box box = new Box(5);
System.out.println("\nA rectangle " + rectangle.toString());
System.out.println("The area is " + rectangle.getArea());
System.out.println("The perimeter is " +rectangle.getPerimeter());
System.out.println("The volume is " + box.getVolume());
}
}
The error is at
public Box(double length){
this.length = length;
}
The error message in Eclipse IDE is as follows:
Implicit super constructor Rectangle1() is undefined. Must explicitly invoke another constructor.
And when I try to run it, it gives me:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Implicit super constructor Rectangle1() is undefined. Must explicitly invoke another constructor
at Box.<init>(Box.java:4)
at TestRectangle.main(TestRectangle.java:7)
Can someone please advise me on how to fix this error?
Your base class Rectangle1 has a constructor:
public Rectangle1(double width, double height) {
this.width = width;
this.height = height;
}
Because you wrote a constructor, the default no aruments constructor will not exist, so super() will not find the right constructor. You should write: super(0, 0) in your Box constructor, which will match Rectangle1 constructor.
Firstly, every subclass must call super(...) as the first statement in every constructor. This is a bit of a pain, so Java adds a call to super() at the start of any constructor that doesn't have a call to super(...). Since Rectangle1 doesn't have a constructor with no arguments, Java's attempt to call super() doesn't work and you need to add your own. Peter and Maroun covered this.
A bigger problem is that you haven't thought about what a Box is. What is a Box(5)? A Rectangle1 has a width and a height, while a Box has a width, a height and a depth. What is shape is a Box(5)? Your Box constructor should be something like
public Box (double width, double height, double depth)
{
super (width, height);
this.depth = depth;
}
In this constructor you can see that the arguments tell you everything you need to know about the Box and the call to super(height, width) takes care of delegating all the rectangle stuff to the base class.
You have to call the super class constructor which you define. The default constructor only exists when you haven't defined one.
Also you should not attempt to initialise fields which are initialised by the parent as this breaks encapsulation. I suggest you do this.
public Box(double length){
super(length, length);
}
This way you are calling a constructor in the super class you have defined and you let it set the fields it is responsible for.