How to use Java Methods/ Parameters - java

I have coded a program using separate parts to find & display the area and perimeter of a rectangle. I am now supposed to create a void to display the length, width, area and perimeter. However, I can't seem to get it to display when I run the program. I will pop in my code and then the instructions of the task underneath in case I haven't explained it well enough.
public class Rectangle
{
public static void main(String[] args)
{
System.out.println (area(10,15));
System.out.println (perimeter(10, 15));
}
/**
* Returns the area of a rectangle
*/
public static int area (int length, int width)
{
return length * width;
}
/**
* Returns the perimeter of the rectangle
*/
public static int perimeter (int length, int width)
{
return 2 * (length + width);
}
public static void printRectangleDetails(int length, int width, int area, int perimeter)
{
System.out.println ("The length of the rectangle is " + length);
System.out.println ("The width of the rectangle is " + width);
System.out.println ("The area of the rectangle is " + area);
System.out.println ("The perimeter of the rectangle is " + perimeter);
}
}
The task information:
"Write a method called printRectangleDetailswhich, when given the height and width of a rectangle, prints four lines of output stating the height, width, area, and perimeter of the rectangle. The output should include suitable text explaining what the numbers area. Add suitable comments to the new method.printRectangleDetails()is a different kind of method fromareaand perimeter. It performs some actions (printing output) but does not return any result when it is called. Its output type must therefore be voidto show that it does not return a value, and it is an example of a void method. A call to a void method can be used as a standalone statement in your program. However, because a void method does not return a value, it cannot be used where an expression with a value is expected. Methods which return a value (non-void methods) can be used as both standalone statements and as expressions."
Edit - I have now seen this on the instructions "Replace the code in the main method with suitable calls of your printRectangleDetails()method." does this mean I should change the void main(String[] args) section to printRectangleDetails() & if so, how would I do this?

Other methods can be called inside methods, you are passing an int area and an int perimeter in your printRectangleDetails parentheses however, you do not have to do this. Your printRectangleDetails method should only know the width and height, and inside the method functions then it will call the other methods area(width, height) and perimeter(width, height) and pass the width and height to them.
For the Edit question, you do not have to change the main(String[] args), but since your new method printRectangleDetails already prints all the info of the rectangle including area and perimeter, then all you have to do is replace any methods inside main with a single call to printRectangleDetails.

Related

Does Java Swing limit how many items it will draw?

I'm writing a recursive method in Java that creates essentially creates a circle tree. It draws a circle at the top and center and then the method gets called again and creates the circles one level lower on the y axis and half way to the left and right of the new circle. I was successful but only for a certain number of objects to be drawn This is what it looks like
public void test(Graphics g, int y, int num, double instance) {
if(num<50) {
int r = 20;
for(int i=1;i<=instance;i++) {
if(i%2==1) {
g.fillOval(getWidth() * i / num, y, r, r);
}
}
if(instance==1){
instance= 2* instance;
}
test(g, y + 20, num * 2, Math.pow(instance,2.0));
}
Everything works perfectly until I try to increase the number in "if(num<50)" to exactly "if(num<65)". When I change that the JFrame appears but now it is empty and it seems like the program is frozen. I want to increase that so that I can fill the Jframe with the circle tree. Why is it doing that? Looking forward to your response! Thank you!
I found the issue. I don't know why I choose to use Math power when I only had to use *2 and that fixed the whole program.

Drivers for Classes in Java “Rectangle"

I’ve never used a separate file for a driver in Java. I’m used to just using a main method. I’ve used separate files in Python but Java is new. Below is my code for each class (“Rectangle” and “Driver”), each from separate files.
Update with the methods changed to static: Don’t pay attention to the change in class names or formatting…I’m just tweaking so it will work with MyProgrammingLab. I still have to add in parameters for length and width being between 0.0 and 20.0 only (easy if-else statements).
import java.util.Scanner;
public class Driver{
public static void main(String[] args) {
Scanner input = new Scanner( System.in);
System.out.print("Enter length of rectangle:");
double length = input.nextDouble();
System.out.print("Enter width of rectangle:");
double width = input.nextDouble();
Rectangle Perimeter = new Rectangle(length, width);
Perimeter.getPerimeter();
Rectangle Area = new Rectangle(length, width);
Area.getArea();
System.out.printf("Area: %.1f, Perimeter: %.1f",Rectangle.getArea(),Rectangle.getPerimeter());
}
}
final class Rectangle {
private static double mLength;
private static double mWidth;
public Rectangle(double length, double width){
mLength = length;
mWidth = width;
}
public double getLength(){
return mLength;
}
public double getWidth(){
return mWidth;
}
public static double getArea(){
double area = mWidth*mLength;
return area;
}
public static double getPerimeter(){
double perimeter = (mWidth*2)+(mLength*2);
return perimeter;
}
}
It makes more sense to create a Rectangle object with it's length & width, so use your overloaded Rectangle constructor by passing the length and width arguments (entered by user) as shown below:
Rectangle Perimeter = new Rectangle(length, width);
the constructor Rectangle() is undefined. Can anyone help?
The important point is that when you have an overloaded constructor like in your Rectangle class (where there are no default i.e., no argument constructors written), you can't create an object using new Rectangle();, this is because compiler doesn't add the default constrcutor automatically for you. I suggest look here for more details on this.
Also, if you wanted to print the Rectangle object with length & width details, you need to override toString() method from java.lang.Object method as shown below:
public class Rectangle {
private double mLength;
private double mWidth;
//add your code here as is
#Override
public String toString() {
return "Rectangle [mLength=" + mLength + ", mWidth=" + mWidth + "]";
}
}
The default constructor is provided by compiler if there are no constructor written explicitly.
But if you explicitly write any constructor in the class, then whenever you call a constructor, be it no-argument or with arguments, it will always look for explicitly defined constructor in class.
And, this is logically correct since, if you want to block creation of objects without any data in it, adding a constructor with argiment is the way to go.
So either explicitly write a no argument constructor in Rectangle and use setter to set its attributs, or just use the argument constructor in your method.
Add to Rectangle.class an empty constructor :
public Rectangle() {
}
Or Use constructor declared with parameters in your method
Rectangle rectangle = new Rectangle(length, width);
In your case you are using the rectangle object wrong.
I think what you looking to do is this :
Rectangle rectangle = new Rectangle(length , width );
System.out.printf("Area: %.1f, Perimeter: %.1f",rectangle.getArea() ,rectangle.getPerimeter());

Java: Creating/Using an Array of Records

I have an assignment that asks us to create a program to compute the dimensions (width and height) of a screen given the diagonal and aspect ratio.
I'm supposed to ask the user for the inputs (diagonal and aspect ratio), call a subprogram to compute the dimensions (height and width), then display the results. The subprogram needs to return both width and height, so I need to create a 'record' that combines the two into one unit. PLEASE HELP!
The formulas are:
x = sqrt(y^2 / (1+ a^2))
h=x
w=ax
where:
h=height
w=width
y=diagonal
a=aspect ratio
Here's what I have so far:
package hw3;
//A. Nelson, a program to compute the dimensions (width & height)
//of a screen given the diagonal & aspect ratio
import java.util.Scanner;
class Screen
{
public int height, width;
}
public class Hw3 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
Screen dimensions = new Screen();
//Variables
int yDiagonal, aAspect;
//Program description
System.out.println("This program will compute the dimensions (width and height)" +
"\nof a screen given the diagonal and aspect ratio.");
//Prompt 1: Diagonal
System.out.print("\nPlease enter the following dimensions:" +
"\n\tDiagonal (inches): ");
yDiagonal = keyboard.nextInt();
//Prompt 2: Aspect
System.out.print("\tAspect Ratio: ");
aAspect = keyboard.nextInt();
//Compute Dimensions
System.out.println("\nHere are the dimensions of the screen:" +
"\nHave a nice day!");
}
public Screen computeDimensions(int yDiagonal,int aAspect)
{
int answer;
answer = (int) Math.sqrt( Math.pow(yDiagonal,2) / (1+Math.pow(aAspect,2)));
Screen [] dimensions = new Screen[2];
Screen.height = answer;
Screen.width = aAspect*answer;
return Screen;
}
}
You have several problems in your code
First, just declaring the method doesn't actually invoke the method (i.e. the method is never executed). So at the end of your main method you need
dimensions = computeDimensions(yDiagonal, aAspect);
However, there are other serious issues.
First, you've declared aAspect as an integer, while screen aspect ratios normally have values that are NOT integer ratios, such as 1920x1080 or 16:9, which is 1.7777... Same for other aspect ratios, so you'll need to accept a floating-point value instead of an integer, or write code to parse strings such as "16:9" and calculate the ratio.
Then inside computeDimensions you create an array of Screen objects, where you only need one. The correct code here is
Screen result = new Screen();
result.height = answer;
result.width = aAspect*answer;
return result;
and then in the main method after the call to computeDimensions you must print the values returned in dimensions.
There could be other problems as well in your definition of the algorithm. I'm not going to write your entire assignment for you, but this should get you pointed in the right direction.
Just in addition to Jim's right answer:
Here is an example on how to call the computeDimensions method from your main method:
public static void main(String[] args) {
...
//Compute Dimensions
Screen s = computeDimensions(yDiagonal, aAspect);
System.out.println("\nHere are the dimensions of the screen: height=" +
s.height + ", width=" + s.width + "\nHave a nice day!");
}
Also, you have to add the keyword static to your computeDimensions method or the program won't compile, because you are calling from a static context:
public static Screen computeDimensions(int yDiagonal,int aAspect) {
...
}

Inheritance of Square method in java

I have a class Rectangle laid out like this:
package Inheritance;
/**
*
* #author Jacob
*/
public class Rectangle {
final private int length;
final private int width;
public Rectangle (int l, int w)
{
length = l;
width = w;
}
public int getLength ()
{
return length;
}
public int getWidth ()
{
return width;
}
#Override
public String toString ()
{
return String.format ("Rectangle (%dX%d)", length, width);
}
}
I then need to create class square in the following way:
ad Square:
Square extends Rectangle /
No fields are declared in class Square /
It has a parameterized constructor with (only) one parameter /
The parameter is used to initialize both fields of Rectangle /
It has a method called getSide to expose the side-length of the square /
Override the toString method so that it will return a String of the following form: / Square(side) e.g. Square(4)
The values for the sides are going to be hard coded. Rectangle is going to have a width of 4. In order to get the side of the square to be 4 do I create an instance of rectangle and call the method getWidth and set that as the side length. Thats how I would think to do it but in that case I would only be using one of the fields so, My question is how do I initialize both fields? Can I call Rectangle and make length and width equal or is there some other way I should do it?
Here is the code for my Square class:
public class Square {
public Square (int side)
{
super(side, side);
}
public int getSide ()
{
return side;
}
#Override
public String toString ()
{
return String.format ("Square (%d)", side);
}
}
For the line super(side, side) I get the error constructor Object in class Object cannot be applied to given types. Required no arguments, found int, int. For my return statements I get that it cannot find the variable side.
The values for the sides are going to be hard coded.
I assume that you mean that you will hardcode the values for the width and length when you create a Rectangle and Square object (for example in main()). These values should absolutely not be hardcoded any where in the Rectangle and Square classes.
Rectangle is going to have a width of 4. In order to get the side of the square to be 4 do I create an instance of rectangle and call the method getWidth and set that as the side length.
Not at all. Rather, Square should have its own constructor which calls the Rectangle constructor with the same value for both the width and length:
public Square(int side) {
super(side, side); // Set the width and length to the same value.
}

Writing class method for test class

public class CirclTest{
public static void main(String[] args){
Circle first=new Circle('R',3.0);
Circle first=new Circle('R',3.0);
Circle second=new Circle();
System.out.println("first's radius is " + first.getRadius());
System.out.println("first's area is " + first.getArea());
System.out.println("second's area is " + second.getArea());
if(first.hasLargerAreaThan(20)){
System.out.println("first's area is larger than 20. ");
}else{
System.out.println("first's area is smaller than 20. ");
}
}
}
So i am supposed to write a circle class.This is what i have done.
public class Circle{
private double radius=0.0;
private double area=0.0;
private char colour=' ';
public Circle(char colour,double radius){
this.colour=colour;
this.radius=radius;
}
public Circle(){
radius=0;
colour='B';
}
public char getColour(){
return colour;
}
public double getRadius(){
return radius;
}
public double getArea(){
return area;
}
}
I am actually confused on how to write a class.Like i know i need to initialize the variables by private etc.And i need to build a constructor but somehow this code above does not work.the test method is correct.But i have to use it to implement my class.
You're declaring the variable
Circle first
twice. If you want to reassign its value, just do
first=new Circle('R',3.0);
And inside the if statement you're calling
first.hasLargerAreaThan(20)
when I don't see such a method defined in your class.
Can you please what you mean by the code does not work? If you are referring to area not getting calculated correct and is always 0, that is happening because you have a default value for the same as 0 and are never calculating it. You might want to put calculation logic in getArea() method.
First, you're going to want to use a testing framework to assert the validity of your code, if that's what is required. Look into JUnit.
A sample assertion of if the area was larger than some value would be written like this.
#Test
public void assertArea_calculatedProperly() {
//given that the radius is 5,
Circle c = new Circle('R', 5);
//when I get the area...
double result = c.getArea();
//then I expect it to be around 78.53981634.
assertTrue(result < 78.6);
assertTrue(result > 78.5);
}
Second, your getArea isn't actually getting the area. There's nothing in your code to retrieve, then calculate the area. You're not even using Math.PI. I would recommend that you implement that - but use the unit test as a valid way to assert that you're going to get an appropriate response back.

Categories

Resources