I am new to programming and recently started on my computer science degree. Due to my son being sick I missed labs yesterday for CS-140/Java and am having a little trouble with my lab assignment from home.
I am told to Construct an empty Rectangle called box.
Figure out how to change the width of box to 50, its height to 60 and top-left corner to [100,50]. (You need to call appropriate methods on box to achieve this.)
Figure out how to compute the area of box. You have to get the height and width of box, by calling appropriate methods to compute the area.
Then print the value returned by calling a method on box and then we print a message that describes the value we expect to see.
I have searched through stack exchange and found some useful information but I still cannot figure out the bugs in the code and why it is not working. I am assuming the 63 errors are from something like a curly bracket in the beginning either missing or too many curly brackets.
I have 63 errors somehow the code I have entered so far is the following:
import java.awt.Rectangle;
public class Rectangle {
public double x;
public double y;
public double width, height;
public Rectangle(double x, double y, double w, double h) {{
this.x = x;
this.y = y;
width = w;
height = h;
}
public static void main(String[] args) {
Rectangle box = new Rectangle (100, 50, 50, 60);
System.out.println(box);
}
System.out.println("Part 1:");
System.out.println("-------");
System.out.println("CREATING AN EMPTY Rectangle, SETTING ITS width TO 50, " +
"ITS height TO 60, AND ITS TOP LEFT CORNER TO (100, 50)");
// Code for Part 1 goes here
}
System.out.println("Part 2:");
System.out.println("-------");
System.out.println("TESTING THE PERIMETER OF THE RECTANGLE "
+ "CREATED IN PART 1 ABOVE");
// Code for Part 2 goes here. Use the same Rectangle
// you used Part1
// define a String reference called river and initialize it
// to Mississippi. Read the API to figure out which method
// to use to get the desired effect.
System.out.println("Part 3:");
System.out.println("-------");
System.out.println("INITIALIZING river to Mississippi AND REPLACING "
+ "EACH i to ! AND EACH s TO $");
// code for Part 3 goes here
System.out.println("Part 4:");
System.out.println("-------");
System.out.println("CONSTRUCTING A StringBuilder OBJECT INITIALIZED "
+ "TO desserts AND REVERSING IT");
// code for Part 4 goes here
System.out.println("Part 5:");
System.out.println("-------");
System.out.println("CONSTRUCTING A Random OBJECT TO PLAY LOTTERY BY GENERATING ");
System.out.println("6 RANDOM INTEGERS BETWEEN 1 and 49 (BOTH INCLUSIVE)");
//code for Part 5 goes here
System.out.println("Part 6:");
System.out.println("-------");
System.out.println("ADDING ONE DAY TO 2/28/2019, 2/28/2020, 2/28/2021 " +
"AND 2/28/2022 AND PRINTING THEM");
// code for Part 6 goes here
}
}
Any help is appreciated. I am excited to join the community of StackOverflow and hopefully be able to contribute someday.
Here is the cleanup of your code:
//import java.awt.Rectangle; // you probably autocompleted this line, since you created your own Rectangle class for console outputs
public class Rectangle {
public double x;
public double y;
public double width, height;
public Rectangle(double x, double y, double w, double h) {
this.x = x;
this.y = y;
width = w;
height = h;
}
public static void main(String[] args) {
Rectangle box = new Rectangle (100, 50, 50, 60);
System.out.println(box);
System.out.println("Part 1:");
System.out.println("-------");
System.out.println("CREATING AN EMPTY Rectangle, SETTING ITS width TO 50, " +
"ITS height TO 60, AND ITS TOP LEFT CORNER TO (100, 50)");
// Code for Part 1 goes here
System.out.println("Part 2:");
System.out.println("-------");
System.out.println("TESTING THE PERIMETER OF THE RECTANGLE "
+ "CREATED IN PART 1 ABOVE");
// Code for Part 2 goes here. Use the same Rectangle
// you used Part1
// define a String reference called river and initialize it
// to Mississippi. Read the API to figure out which method
// to use to get the desired effect.
System.out.println("Part 3:");
System.out.println("-------");
System.out.println("INITIALIZING river to Mississippi AND REPLACING "
+ "EACH i to ! AND EACH s TO $");
// code for Part 3 goes here
System.out.println("Part 4:");
System.out.println("-------");
System.out.println("CONSTRUCTING A StringBuilder OBJECT INITIALIZED "
+ "TO desserts AND REVERSING IT");
// code for Part 4 goes here
System.out.println("Part 5:");
System.out.println("-------");
System.out.println("CONSTRUCTING A Random OBJECT TO PLAY LOTTERY BY GENERATING ");
System.out.println("6 RANDOM INTEGERS BETWEEN 1 and 49 (BOTH INCLUSIVE)");
//code for Part 5 goes here
System.out.println("Part 6:");
System.out.println("-------");
System.out.println("ADDING ONE DAY TO 2/28/2019, 2/28/2020, 2/28/2021 " +
"AND 2/28/2022 AND PRINTING THEM");
// code for Part 6 goes here
}
}
The assignments are as follows:
//assignment 1
Rectangle box = new Rectangle(0,0,0,0);
//assignment 2
box.width = 50;
box.height = 60;
box.x = 100;
box.y = 150;
//assignment 3
int area = box.height*box.width;
//assignment 4
System.out.println("Area: "+area);
I'm sure you can integrate this into your own code and make the appropriate methods as well as getters and setter if needed.
The answers to all of these questions can be found on the Java documentation for Rectangle. I don't want to spoonfeed, so here's some of my observations.
Use one of the constructors to set dimensions.
Use some of the methods to read each dimension (height, width, etc)
Calculate using formula for area.
Related
Sorry to trouble but it seems I'm a little lost.
I am currently creating a Shape Calculator for 2D and 3D shapes and I seem to be having a problem with the above mentioned shapes in the title.
Now I have gone about trying to use this particular section of code to get the Area of my Pentagon, I've seen this work elsewhere but can't figure out why it won't work here even after reviewing and comparing my code? I thought someone could possibly point out if this is the correct way to go about solving it or if I've made a mistake I can't see myself? Generally need a second opinion sorry.
double pen = scan.nextDouble();
double penPerm = pen * 5;
double A1 = pen * Math.sqrt(5);
double A2 = 5 + A1;
double A3 = Math.sqrt(5 * A2);
double PenA = (1.0 / 4.0) * A3 * Math.pow(pen, 2);
System.out.println("Your Perimitre is :" + penPerm + "cm and your Area is :" + PenA + "cm Squared");
The other problem I have how should I go about tackling the Hexagon but to be honest, the above Pentagon problem is my main concern before I move onto the Hexagon.
For a regular pentagon you can try the following code:
public static void main(String[] args) {
double side = 10;
double area = (1.0/4.0) * Math.sqrt(5*(5+2*Math.sqrt(5))) * Math.pow(side,2);
System.out.println("Your Perimitre is :" + 5*side + "cm and your Area is :" + area + "cm Squared");
}
You can also try the following code which takes no of sides (n) and edge size (s) as input and computes area for a regular polygon:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println(" Enter the number of sides in polygon");
int n = input.nextInt();
System.out.println(" Enter the distance between two points");
double s = input.nextDouble();
double area = (n * Math.pow(s, 2)) / (4 * Math.tan(Math.PI / n));
//Print result
System.out.println (" Area is " + area);
System.out.println (" Perimeter is " + s*n);
}
The following code is what I'm having issues understanding:
public class Rectangle {
public Rectangle() {
double width = 1;
double height = 1;
}
public Rectangle(double w, double h) {
double width = w;
double height = h;
}
public double getArea(double w, double h) {
return (w*h);
}
public double getPerimeter(double w, double h) {
return ((2*w)+(2*h));
}
public static void main(String[] args) {
Rectangle oldRectangle = new Rectangle(4, 40);
Rectangle newRectangle = new Rectangle(3.5, 35.9);
double height1 = oldRectangle.height;
double height2 = newRectangle.height;
double width1 = oldRectangle.width;
double width2 = newRectangle.width;
System.out.println("Width of Rectangle 1 is: " + 4);
System.out.println("Height of Rectangle 1 is: " + 40);
System.out.println("Area of Rectangle 1 is: " + oldRectangle.getArea(4, 40));
System.out.println("Perimeter of Rectangle 1 is: " + oldRectangle.getPerimeter(4, 40));
System.out.println("Width of Rectangle 1 is: " + 3.5);
System.out.println("Height of Rectangle 1 is: " + 35.9);
System.out.println("Area of Rectangle 1 is: " + newRectangle.getArea(3.5, 35.9));
System.out.println("Perimeter of Rectangle 1 is: " + newRectangle.getPerimeter(3.5, 35.9));
}
}
I was instructed to create two constructors for a Rectangle class—one with no arguments but assigned a default value of 1 for both variables width and height. The second constructor was to contain parameters that would take in two doubles that would get assigned to their appropriate variable.
I was then told to create two 'get()' methods that returned their respective values—in my case, they were perimeter and area of said Rectangle.
I was then instructed to create two Rectangle instances, one with a width of 4 and a height of 40—and another with a width of 4.5 and a height of 35.9. So, I did just that and made two new Rectangle objects, as you can see.
Lastly, I was instructed to print out the Width, Height, Perimeter, and Area of both Rectangle objects. My issue is that I don't know of a way to reference them. I took a beginners tutorial class for JavaScript and if I'm not mistaken, I recall there was a way to reference a property value of an object by assigning it to a variable. Again, I'm saying "If I'm not mistaken", so I could be wrong. It's been a while...
I do realize that Java and Java Script are entirely different things in their own right. Java Script was a scripting language developed and based off of Java.
Anyway, any help will be grand.
Please feel free to help me understand how I can implement what I'm trying to do by giving examples. You don't have use my exact code, but I'd like to be able to get my code to make more sense.. I'm using Eclipse btw.
You are on the right track. What you are looking to do is something like this:
public double getArea(Rectangle r){
return r.width*r.height;
}
public double getPerimeter(Rectangle r){
return (2*r.width + 2*r.height);
}
For the print statements you are hard-coding in values which you dont have to do.
System.out.println("Width of Rectangle 1 is: " + oldRectangle.width);
System.out.println("Height of Rectangle 1 is: " + oldRectangle.height);
System.out.println("Area of Rectangle 1 is: " + getArea(oldRectangle));
System.out.println("Perimeter of Rectangle 1 is: " + getPerimeter(oldRectangle));
My issue is that I don't know of a way to reference them
As Java is a strong-typed language, to store the references to each Rectangle (or any object) attribute, you must create variables that match the field.
First, you need your rectangle have attributes:
public class Rectangle {
public double width;
public dobule height;
// constructors here...
After, methods to calculate area and perimeter:
public double getArea() {
return (width*height);
}
public double getPerimeter() {
return ((2*width)+(2*height));
}
Now, to reference them (i guess you still mean area and perimeter):
double area1 = getArea(newRectangle);
double area2 = getArea(oldRectangle);
and
double perimeter1 = getPerimeter(newRectangle);
double perimeter2 = getPerimeter(oldRectangle);
There are no width and height properties in your class, they are only defined inside the constructor, declare them in the class and not inside the constructors so you can acces them like this:
public class Rectangle {
double width;
double height;
public Rectangle() {
width = 1;
height = 1;
}
public Rectangle(double w, double h) {
width = w;
height = h;
}
public double getArea(double w, double h) {
return (w*h);
}
public double getPerimeter(double w, double h) {
return ((2*w)+(2*h));
}
//....
}
Note: It's better to declare them as private and use getters and setters to acces them, take a look at Adding Setter and Getter Methods for further information.
EDIT:
In your case you don't need to pass parameters to your methods (because the calculation needs this rectangle width and height), just calculate them using your class fields, like this:
public double getArea() {
return (width*height);
}
public double getPerimeter() {
return ((2*width)+(2*height));
}
Here's what you need to do to acces your variables:
public static void main(String[] args) {
Rectangle oldRectangle = new Rectangle(4, 40);
Rectangle newRectangle = new Rectangle(3.5, 35.9);
//In the following you access all the object variables and methods
System.out.println("Width of Rectangle 1 is: " + oldRectangle.width);
System.out.println("Height of Rectangle 1 is: " + oldRectangle.height);
System.out.println("Area of Rectangle 1 is: " + oldRectangle.getArea());
System.out.println("Perimeter of Rectangle 1 is: " + oldRectangle.getPerimeter());
System.out.println("Width of Rectangle 1 is: " + newRectangle.width);
System.out.println("Height of Rectangle 1 is: " + newRectangle.height);
System.out.println("Area of Rectangle 1 is: " + newRectangle.getArea());
System.out.println("Perimeter of Rectangle 1 is: " + newRectangle.getPerimeter());
}
You can test the DEMO here.
And to answer your question about using constructor, calling the parametrized constructor like this:
Rectangle oldRectangle = new Rectangle(4, 40);
Is equivalent to:
// create the object
Rectangle oldRectangle = new Rectangle();
//And then assigning the values 4 and 40 to its width and height
oldRectangle.width=4;
oldRectangle.height=40;
I have an assignment that I am having trouble figuring out.
Write an application (Rectangle.java) that asks the user to enter the length and the width of a rectangle (both are positive double-precision floating-point numbers), and prints the area and perimeter of the rectangle. When the user enters 7.9 and 4.5, the output of your program should look exactly like the following:
Enter the length and the width of a rectangle: 7.9 4.5
The area of the rectangle is 35.55.
The perimeter of the rectangle is 24.80.
The part I am having trouble with is bringing the output of the perimeter of the rectangle out to two decimal places including the "0." I have been trying to figure it out for so long. I know there must be a simple efficient way to do this or it would not be assigned to us as our second Java homework assignment. If it is to format it as %2d i do not know how to apply that to what i have. I REALLY appreciate your help!
Here is what i have so far:
import java.util.Scanner;
public class Rectangle {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the length and the width of a rectangle: ");
double length = input.nextDouble();
double width = input.nextDouble();
double area = (length * width);
double perimeter = (length * 2 + width * 2);
System.out.println("The area of the rectangle is " + (int)(area * 100) / 100.0 + ".");
System.out.println("The perimeter of the rectangle is " + (int)(perimeter * 100) / 100.0 + ".");
}
}
My Output:
Enter the length and the width of a rectangle: 7.9 4.5
The area of the rectangle is 35.55.
The perimeter of the rectangle is 24.8.
You need %.2f in format:
System.out.printf("The perimeter of the rectangle is %.2f", 24.8);
The 24.8 is just for test, you may replace it with the correct expresion.
Read the documentation about String.format() and the format string syntax. This will help you find the right format string to output the numbers as required.
Basically you'd have to have the last two lines of code to:
System.out.println("The area of the rectangle is " + String.format("%.2f", area) + ".");
System.out.println("The perimeter of the rectangle is " + String.format("%.2f", perimeter) + ".");
I was making a random line generator for fun, and when I run the program, the "Y (End): " string looks very strange. The numbers are displayed as rectangular symbols, that have no meaning.
Here is my code:
public class LineFractal extends Applet {
Random random = new Random();
int width = 640;
int height = 640;
int x = 1000;
int endy1 = random.nextInt(width/2);
int endx1 = random.nextInt(width/2);
int starty1 = random.nextInt(width/2);
int startx1 = random.nextInt(width/2);
int space = random.nextInt(25);
public void init() {
setSize(width, height);
Frame c = (Frame)this.getParent().getParent();
c.setTitle("Line Generator");
}
public void paint(Graphics g) {
while (x > 0) {
x -= 1;
g.drawLine(startx1, starty1, endx1, endy1);
g.drawString("Space: " + space, width-100, height-10);
g.drawString("Y (End): " + endy1, width-100, height-20);
endy1 += space;
endx1 -= space;
}
}
}
Why does it do this?
EDIT: Just tried the program again, and the y was actually displayed correctly for once. But then I ran it again, and only the last number could be seen. The last time I ran it, there were no numbers that were readable...
You seem to be printing the string Y (End) and then a number over the top of itself 1000 times. Obviously that's OK for the text, but the number part is going to look messy very quickly! Imagine writing 0 1 2 3 4 5 6 7 8 9 all on top of each other.
You probably mean to draw a white (or whatever background colour) filled rectangle to the area where the strings are to be printed, just to clear what's there already.
I fixed it by putting the two drawString() outside the while loop.
I have to ask the user to input the dimensions of two boxes then calulate the surface area and volume of two boxes. I am done with everything but i keep getting the error: constructor Box in class Box cannot be applied to given types:
My main class BoxCalc:
package boxcalc;
import cs1.Keyboard;
public class BoxCalc
{
public static void main(String[] args)
{
int width, length, height, volume1, volume2, surfacearea1, surfacearea2;
Box b1 = new Box();
Box b2 = new Box();
b1.getClass();
b2.getClass();
// Ask the user the demensions for Box 1.
System.out.println ("Box 1");
System.out.print ("Enter a value for the height of Box 1: ");
height = Keyboard.readInt();
System.out.println ("Enter a value for the length of Box 1: ");
length = Keyboard.readInt();
System.out.println ("Enter a value for the width of Box 1: ");
width = Keyboard.readInt();
// Calulating the volume and the surface area of Box 1.
volume1 = width*height*length;
surfacearea2 = (2*(length * height))+(2 *(length * width))+
(2*(width*height));
// Ask the user the demensions for Box 2.
System.out.println ("Box 2");
System.out.print ("Enter a value for the height of Box 2: ");
height = Keyboard.readInt();
System.out.println ("Enter a value for the length of Box 2: ");
length = Keyboard.readInt();
System.out.println ("Enter a value for the width of Box 2: ");
width = Keyboard.readInt();
// Calulating the volume and the surface area of Box 2.
volume2 = width*height*length;
surfacearea2 = (2*(length * height))+(2 *(length * width))+
(2*(width*height));
// Determain which Box has greater volume.
if (volume1 > volume2)
{
System.out.println("Box 1's volume is greater!");
}
else
if(volume2 > volume1)
{
System.out.println("Box 2's volume is greater!");
}
if(volume1 == volume2)
{
System.out.println("Box 1's volume is same as Box 2's!");
}
// Display all the information.
System.out.println();
System.out.println(b1);
System.out.println();
System.out.println(b2);
}
}
My class Box:
package boxcalc;
public class Box
{
private int width, length, height, volume, surfacearea;
// Defining the width, length, and height.
public Box (int boxwidth, int boxlength, int boxheight)
{
width = boxwidth;
length = boxlength;
height = boxheight;
}
// Method to calulate the volume.
public void findVolume(int volume)
{
volume = length * height * width;
}
// Method to calulate the surface area.
public void findSurfaceArea(int surfacearea)
{
surfacearea = (2*(length * height))+(2 *(length * width))+
(2*(width*height));
}
// Use toString method to display all the info above.
public String toString()
{
return ("Length: " + length + "\n" + "Width: " + width + "\n" +
"Height: " + height + "\n" + "Volume: " + volume +"\n" +
"Surface area: " + surfacearea + "\n");
}
}
your box constructor:
public Box (int boxwidth, int boxlength, int boxheight)
{
width = boxwidth;
length = boxlength;
height = boxheight;
}
but you creating box object with no parameter:
Box b1 = new Box();
Box b2 = new Box();
it should be:
after you ask user for the dimension of box 1, put this:
Box b1 = new Box(width, length, height);
after you ask user for the dimension of box 2, put this:
Box b2 = new Box(width, length, height);
As it stands, your program isn't object-oriented in the slightest.
There was no point in posting your Box class, as your main program doesn't make use of it in any significant way.
You're determining which box is bigger in a structured programming manner, by declaring enough variables in main to do all of the logic.
You should get all the dimensions for box1, then do this:
Box b1 = new Box(width, height, length);
Then do the same for box2, and again:
Box b2 = new Box(width,height,length);
Then, in your if statements, instead of volume1 > volume2, you should instead be doing something more like this:
if(b1.getVolume() > b2.getVolume())
Where getVolume() should be a method of your Box class that looks like this:
public int getVolume() {
return volume;
}
(Although, best practices might say don't even include a volume variable in the Box class, and simple do return (width * height * length);
The same principles should be applied to other aspects of your program.
As a note, by doing it this way, your main program only needs 3 int variables: width, height, length. Once you send b1's dimension into the constructor, the b1 variables knows its dimensions, and you can reuse these variables for taking in b2's dimensions. You don't need volume1, volume2, surfacearea1, or surfacearea2 variables, because a complete Box class would allow you to get these Box properties via getVolume() and getSurfaceArea().
You are calling the Box constructor with no parameters: Box b1 = new Box();, and in the class itself it is defined as requiring to have multiple (three) numeric parameters: public Box (int boxwidth, int boxlength, int boxheight). So the compiler is rightfully complaining that something is amiss.
Possible Solutions:
When you call the constructor, pass in 3 numbers that make sense. Edit: and do this after the user has entered valid data.
Or give Box a default constructor that takes no parameters and sets its fields to some default values.