Static method to turn shapes red - java

so i made this program and i am trying to add in my testing file a static method that turns a random array of shapes all "red".
public abstract class Shape
shape class
public abstract class Shape
{
private String color;
public Shape() { color = "white";}
public String getColor() { return color;}
public void setColor(String c) { color = c; }
public abstract double area();
public abstract double perimeter();
public abstract void display();
}
circle class
public class Circle extends Shape {
private double radius;
public Circle( double r)
{
super();
radius = r;
}
public double getRadius()
{ return radius; }
//Implement area, perimeter and display
public double area()
{
return Math.PI * radius* radius;
}
public double perimeter()
{
return 2* Math.PI *radius;
}
//Circle class - continued
public void display()
{
System.out.println( this);
}
public String toString()
{
return "Circle: radius:" + radius
+ "\tColor: " + getColor();
}
}
my main class for testing
public class TestingShapes {
public static double sumArea( Shape[] b)
{
double sum = 0.0;
for( int k = 0; k < b.length; k++)
{
sum = sum + b[k].area();
}
return sum;
}
public static void printArray( Shape[] b)
{
for (Shape u: b)
System.out.println(u + "\tArearea " + u.area());
System.out.println();
}
public static void main( String[] args)
{
Shape[] list = new Shape[20]; //Not creating Shapes
for ( int k = 0 ; k < list.length; k++)
{
double z = Math.random();
if( z < 0.33 )
list[k] = new Circle(1 + Math.random() * 10);
else if(z<0.66)
list[k] = new Rectangle ( 3*(k+1), 4*(k+1), 5*(k+1),6*(k+1));
else
list[k] = new Triangle ( 3*(k+1), 4*(k+1), 5*(k+1));
}
printArray(list);
System.out.println();
double sum = sumArea(list);
System.out.println("Sum of List Area: " + sum);
}

To turn some shapes randomly red, you would create a method accepting the array of shapes, and loop over it. You can use Math.random() to get a random floating point number between 0 and 1. To turn, say, 20% of shapes red, you would just compare Math.random() to 20%: if (Math.random() < 0.2) { call the shape's setColor method with "red" }. Since arrays/collections in Java are passed by reference, you don't need to return anything from the method, it will modify the copy that the caller owns.

Related

I need to be able to find the smallest volume in an ArrayList using a for-each loop

This is the code I have done so far. It creates the ArrayList and adds the circles. The volume is stored and is printed in the console. The last thing I have to do is print out the smallest volume using a for-each loop. This is where I'm having difficulties. I could really use some help/advice
public static void main(String[] args)
{
Random rand = new Random();
final int RADIUS_MAX = 100;
int NUM_SPHERES = 4;
List<Sphere> spheres = new ArrayList<Sphere>();
for(int add = 1; add <= NUM_SPHERES; add++) {
spheres.add(new Sphere(rand.nextInt(RADIUS_MAX)));
}
for (Sphere s : spheres) {
System.out.println(s);
}
//TODO: Convert to a for-each loop to find the volume of the smallest sphere
for (Sphere s : spheres) {
}
}
You do not need an additional loop. The sphere with the smallest radius will have the smallest volume. You could store the smallest volume so far (initialized to a very large volume) and update it in either of your existing loops. I believe the formula for volume is (4. / 3) * Math.PI * Math.pow(radius, 3).
The volume formula of the sphere depends from radius like V <=> R, so no need to calculate volume each time, because minimal voule will be with minimal radius.
public class Foo {
public static void main(String... args) {
Random rand = new Random();
final int maxRadius = 100;
final int totalSphere = 4;
List<Sphere> spheres = new ArrayList<>();
for (int i = 0; i < totalSphere; i++)
spheres.add(new Sphere(rand.nextInt(maxRadius)));
for (Sphere sphere : spheres)
System.out.println(sphere);
Sphere smallestSphere = spheres.get(0);
for (Sphere sphere : spheres)
if (smallestSphere == null || sphere.compareTo(smallestSphere) < 0)
smallestSphere = sphere;
System.out.println("smallest volume: " + smallestSphere.getVolume());
}
public static class Sphere implements Comparable<Sphere> {
private final int radius;
public Sphere(int radius) {
this.radius = radius;
}
public double getVolume() {
return (4. / 3) * Math.PI * Math.pow(radius, 3);
}
#Override
public String toString() {
return "radius: " + radius;
}
#Override
public int compareTo(Sphere sphere) {
return Integer.compare(radius, sphere.radius);
}
}
}

Size comparisons (circumference/square perimeter) etc

3 diffrent classes 1 for handling Circle isntances ,1 for Square instances and the 3rd for comparrisons between them(main) . In the main function i find the circle (between c1..c4) and square (between s1...s5) and print the biggest circumference and area of them respectively.[so circle-circle and square-square comparison]
!!!! NOTE : Only the ones with the biggers radius or sides have the biggest circumference or area , so i only use r and a for comparisons.i dont know if its possible to return this if i use the area/circumference method(no , cause then i will only handle numbers ?).Correct me please.
Now i want to print the characteristics(x,y,r/a) of the geometric shape (circle/square) with the biggest perimeter. How can i do this ? Where do i compare?New class?[square-circle comparison]
public class Circle {
public double x,y,r;
public double circumference() {
return 2*(3.14)*r;
}
public double area() {
return 3.14*r*r;
}
public Circle bigger(Circle c){
if(c.r>r) return c; else return this;
}
public Circle(double x, double y, double r) {
this.x=x;
this.y=y;
this.r=r;
}
}
public class Square {
public double x,y,a;
public double perimeter() {
return 4*a;
}
public double area() {
return a*a;
}
public Square bigger(Square s){
if(s.a>a) return s; else return this;
}
public Square(double x, double y, double a) {
this.x=x;
this.y=y;
this.a=a;
}
}
public class CircleAndSquareTest {
public static void main(String[] args) {
Circle c1 = new Circle(0.0,0.0,1.0);
Circle c2 = new Circle(1.0,0.0,2.0);
Circle c3 = new Circle(0.0,2.0,4.0);
Circle c4 = new Circle(1.0,3.0,1.0);
Circle cb = c1.bigger(c2).bigger(c3).bigger(c4);
System.out.println("The circle with the biggest circumference has:\n");
System.out.println("x-axis value: " + cb.x + " y-axis value: " + cb.y + " radius: " + cb.r+"\n");
Square s1 = new Square(0.0,0.0,1.0);
Square s2 = new Square(0.0,0.0,1.0);
Square s3 = new Square(0.0,0.0,5.0);
Square s4 = new Square(4.0,2.0,2.0);
Square s5 = new Square(0.0,0.0,1.0);
Square sb = s1.bigger(s2).bigger(s3).bigger(s4).bigger(s5);
System.out.println("The square with the biggest area has:\n");
System.out.println("x-axis value: " + sb.x + " y-axis value: " +
sb.y + " side: " + sb.a);
}
}
Here's how to do it using Comparators and the Collections class to find the max value. This is untested but it should do what you want. Note I'm using static inner classes here but they can be standard classes defined in their own file if needs be - this is just for the purpose of creating a quick answer.
public interface Shape {
double getPerimeter();
double getArea();
}
public static class PerimeterComparator implements Comparator<Shape> {
#Override
public int compare(Shape a, Shape b) {
return Double.compare(a.getPerimeter(), b.getPerimeter());
}
}
public static class AreaComparator implements Comparator<Shape> {
#Override
public int compare(Shape a, Shape b) {
return Double.compare(a.getArea(), b.getArea());
}
}
public static class Circle implements Shape {
private final double x, y, r;
#Override
public double getPerimeter() {
return 2 * (3.14) * r;
}
#Override
public double getArea() {
return 3.14 * r * r;
}
public Circle(double x, double y, double r) {
this.x = x;
this.y = y;
this.r = r;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
public double getR() {
return r;
}
}
public static class Square implements Shape{
private final double x, y, a;
#Override
public double getPerimeter() {
return 4 * a;
}
#Override
public double getArea() {
return a * a;
}
public Square(double x, double y, double a) {
this.x = x;
this.y = y;
this.a = a;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
public double getA() {
return a;
}
}
public static void main(String[] args) {
List<Shape> shapes = new ArrayList<>();
List<Circle> circles = new ArrayList<>();
circles.add(new Circle(0.0,0.0,1.0));
circles.add(new Circle(1.0,0.0,2.0));
circles.add(new Circle(0.0,2.0,4.0));
circles.add(new Circle(1.0,3.0,1.0));
Circle largestCircle = Collections.max(circles, new PerimeterComparator());
System.out.println("The circle with the biggest circumference has:\n");
System.out.println("x-axis value: " + largestCircle.getX() + " y-axis value: " + largestCircle.getY() + " radius: " + largestCircle.getPerimeter() +"\n");
List<Square> squares = new ArrayList<>();
squares.add(new Square(0.0,0.0,1.0));
squares.add(new Square(0.0,0.0,1.0));
squares.add(new Square(0.0,0.0,5.0));
squares.add(new Square(4.0,2.0,2.0));
squares.add(new Square(0.0,0.0,1.0));
Square largestSquare = Collections.max(squares, new PerimeterComparator());
System.out.println("The square with the biggest area has:\n");
System.out.println("x-axis value: " + largestSquare.getX() + " y-axis value: " + largestSquare.getY() + " side: " + largestSquare.getA());
shapes.addAll(circles);
shapes.addAll(squares);
Shape largestPerimeter = Collections.max(shapes, new PerimeterComparator());
Shape largestArea = Collections.max(shapes, new AreaComparator());
System.out.printf("\nThe shape with the biggest perimeter is a %s and has has: a perimeter of: %f\n", largestPerimeter.getClass().getSimpleName(), largestPerimeter.getPerimeter());
System.out.printf("The shape with the biggest area is a %s and has has: an area of: %f\n", largestArea.getClass().getSimpleName(), largestArea.getArea());
}
Start by declaring a base interface, maybe called Shape that defines a method getPerimeterLength() for example.
Have all your shape classes implement that interface, and the corresponding method(s).
Now, a Square is also a Shape, and so is a Circle. Then you could put all these objects into an array of Shape. You iterate that array, and identify that entry with the maximum perimeter length. Then you simply call toString() on that object. Because you also overwrite the toString() method in all your classes to print the (different!) details each class has internally.

Java error unable to identify mistake

This is Java code, I have created 4 classes 3 constructor and I am getting error of:
method area in class Rect cannot be applied to given types
There is a similar error for rest of 2 class as well. In this program basically I have created 4 classes, 1 for calculating area of rect, 1 for calculating area of Tri and 1 for calculating area of Square and last one is to access main function.
I have created 3 constructor for all the 3 classes rect tri and square and I am unable to spot the mistake in this program.
class Rect //1st class rect
{
double l, b; //variables
Rect(double l, double b) //constructor for rect
{
this.l = l;
this.b = b;
}
double area(double l, double b) //method to cal Rect area
{
return l * b;
}
}
class Square //square class
{
double s;
Square(Double s) //constructor for class
{
this.s = s;
}
double area(double s) //method to cal area for square
{
return s * s;
}
}
class Tri // class for triangle
{
double l, b, h; //variables
Tri(double l, double b, double h) // constructor for tri
{
this.l = l;
this.h = h;
this.b = b;
}
double area(double l, double b, double h) //method to cal area for tri
{
return 0.5 * l * b * h;
}
}
class Area3 {
public static void main(String args[]) {
Rect r = new Rect(10, 10); //constructor initialization for Rect
Square s = new Square(15.0);//constructor initialization for Square
Tri t = new Tri(10.0, 20.0, 30.0);//constructor initialization for Tri
System.out.print(" " + r.area() + "" + s.area() + "" + t.area()); //print areas
}
}
Your area method declarations state that the area methods take in arguments. With those declarations you can't say
Rect r = new Rect(1,4);
r.area();
Simply remove the double argument values from the area methods
You have to create area method without parameters, here the solution,
class Rect // 1st class rect
{
double l, b; // variables
Rect(double l, double b) // constructor for rect
{
this.l = l;
this.b = b;
}
double area(){
return this.l * this.b;
}
double area(double l, double b) // method to cal Rect area
{
return l * b;
}
}
class Square // square class
{
double s;
Square(Double s) // constructor for class
{
this.s = s;
}
double area(){
return this.s * this.s;
}
double area(double s) // method to cal area for square
{
return s * s;
}
}
class Tri // class for triangle
{
double l, b, h; // variables
Tri(double l, double b, double h) // constructor for tri
{
this.l = l;
this.h = h;
this.b = b;
}
double area(){
return 0.5 * this.l * this.b * this.h;
}
double area(double l, double b, double h) // method to cal area for tri
{
return 0.5 * l * b * h;
}
}
class Area3 {
public static void main(String args[]) {
Rect r = new Rect(10, 10); // constructor initialization for Rect
Square s = new Square(15.0);// constructor initialization for Square
Tri t = new Tri(10.0, 20.0, 30.0);// constructor initialization for Tri
System.out.print(" " + r.area() + " and " + s.area() + " and " + t.area()); // print
// areas
}
}
Hope this help, BTW it's work in my PC.
look at your contractors, they all receive an arguments.
and all your area()'s are getting also a arguments.
but!! in your main, you are calling the area() and do not give any values.
just delete from area()'s functions the receiving arguments.

Creating a method to increase height and width of an oblong by amounts entered by the user

Ok so for class I have been working on some oblong questions based off an oblong class. The question I am having an issue with is to create a method to increase the height and width of the oblong by a user defined amount.
This is my main:
import java.util.Scanner;
public class Oblong6
{
public static void main(String [] args)
{
Oblong ob1 = new Oblong();
Scanner keyboardIn = new Scanner(System.in);
Oblong ob = new Oblong();
double h, w, x;
System.out.print ("Enter the height of the oblong:");
h = keyboardIn.nextDouble();
System.out.print ("Enter the width of the oblong:");
w = keyboardIn.nextDouble();
System.out.print (" Enter the amount to increment by ");
x = keyboardIn.nextInt();
ob.setHeight(h);
ob.setWidth(w);
ob.setX(x);
System.out.println (ob.incHeight());
System.out.println (ob.incWidth());
System.out.println("Height " + h);
System.out.println("Width " + w);
}
}
And this is the method I have created in the oblong class to increase them:
public class Oblong
{
// instance variables
private double height;
private double width;
private double x;
// constructor
public Oblong()
{
height = 0.0;
width = 0.0;
x = 0.0;
}
// methods
public double getHeight()
{
return height;
}
public double getWidth()
{
return width;
}
public double setX(double x)
{
return x;
}
public void setWidth(double w)
{
width = w;
}
public void setHeight(double h)
{
height = h;
}
public double calculateArea()
{
return width * height;
}
public double calculatePerimeter()
{
return width + height * 2;
}
public boolean isSquare()
{
if(height == width)
{
return true;
}
else
{
return false;
}
}
public double incHeight()
{
{
return height + x ;
}
}
public double incWidth()
{
{
return width + x ;
}
}
}// end of class
but it only ever prints out the original height and width.
Your code:
public double incHeight()
{
{
return height + x ;
}
}
That just adds two numbers and returns the result.
It doesn't do anything else. The same is true for your other methods.
Whereas the purpose of the method seems to be to alter the state of the underlying object. But as said; the current implementation does not alter that state.
Hope that is good enough to help you to resolve your problem on your own.
Side note: read about Java syntax. Your extra pair of braces ... doesn't do anything either.
Whit this:
public double incWidth()
{
{
return width + x ;
}
}
You are returning width + 1 but you are not modifying the private attribute. Just do this:
public double incWidth(){
this.width = this.width + 1;
return this.width;
}
Also in setters you don't need to return anything. To change an attribute inside a class do something like:
private double value;
private void setValue( double value ) {
this.value = value;
}
With this.value you are refering to the private value inside the class. Without this you are refering to the parameter value of the method setValue.
Further reading:
How do getters and setters work?
Your instance variable x has not been set, hence the height + x will return height + 0.0.
change this:
public double setX(double x)
{
return x;
}
To this:
public double setX(double x)
{
this.x = x;
}
This will return value to be displayed, but it should be set for later use, so you need this :
public void incHeight()
{
setHeight(height + x) ;
}
and then :
System.out.println("Height " + height); // height not h

How to create an array of Rectangles with a Rectangle class?

I'm working on an assignment that is supposed to return an array of 10 rectangles with a random height, random width, and random color selected from a string.
The program works fine to return the objects for ONE rectangle, but how would I implement this to create an array of 10 rectangles and THEN return each one in a loop?
Here's my class file with my objects:
import java.util.*;
public class Rectangle
{
private double width;
private double height;
public static String color = "White";
private Date date;
Rectangle() {
width = 1;
height = 1;
date = new Date();
}
Rectangle (double w, double h) {
width = w;
height = h;
date = new Date();
}
public double getHeight() {
return height;
}
public void setHeight(double h) {
height = h;
}
public double getWidth() {
return width;
}
public void setWidth(double w) {
width = w;
}
public static String getColor() {
return color;
}
public static void setColor(String c) {
color = c;
}
public Date getDate() {
return date;
}
public void setDate (Date d) {
date = d;
}
public double getArea() {
return width * height;
}
public double getPerimeter() {
return 2 * (width + height);
}
public String toString() {
String S;
S = "Rectangle with width of " + width;
S = S + " and height of " + height;
S = S + " was created on " + date.toString();
return S;
}
}
Here is my client program so far. I am setting a random height and a random width and selecting a random color from the colors String.
I would like to be able to do this for an array of 10 different rectangles:
import java.util.*;
public class ClientRectangle
{
public static void main(String[] args)
{
String[] colors = {"White","Blue","Yellow","Red","Green"};
Rectangle r = new Rectangle();
int k;
for(int i = 0; i < 10; i++)
{
r.setWidth((Math.random()*40)+10);
r.setHeight((Math.random()*40)+10);
System.out.println(r.toString() + " has area of " + r.getArea() + " and perimeter of " + r.getPerimeter());
k = (int)(Math.random()*4)+1;
System.out.println(colors[k]);
}
}
}
Thanks!
Create an array of rectangles and add a rectangle to each index.
Rectangle[] arr = new Rectangle[10];
for(int i = 0; i < 10; i++)
{
Rectangle r = new Rectangle();
r.setWidth((Math.random()*40)+10);
r.setHeight((Math.random()*40)+10);
arr[i] = r;
}
Move the Rectangle r = new Rectangle(); inside the for loop. Initialise a Array(List) outside the loop, and keep adding the Rectangles in the loop to the array.
You already seem to know how to declare an array of objects because you did so with an array of Strings. The declartion for an array of Rectangles is very similar:
Rectangle[] rects;
Note that you must also initialize the array. Since arrays are themselves objects you use the new operator, somewhat like when you initialize a reference variable to a single Rectangle:
Rectangle[] rects = new Rectangle[SIZE];
The only difference, as you can see, is that you put the size of the array inside the []s. This only creates an array of references to Rectangle objects. The references are all automatically set to null. This means that you need to create the Rectangles themselves. You can do this in for loop:
for (int i = 0; i <= SIZE; ++i) {
rects[i] = new Rectangle();
}
You can also set the width and height of each Rectangle as you want. (I will leave the exact details about how to do this to the reader.)
Finally, you need to put this all in a method other than main() so that you can return the whole array (You don't return one Rectangle at a time) as the instructions state:
return rects;

Categories

Resources