add object directly in a array - java

I have written a object for a school assignment. now i'm trying to add it to an array so i can add multiple boxes.
my main
String name;
double userInputLength;
double userInputWidth;
double userInputHeight;
// initialise a scanner to be able to read the user input
Scanner reader = new Scanner(System.in);
// ask the user for input
System.out.print ("Enter the name of your box: ");
// read this input
name = (reader.nextLine());
// ask the user for input
System.out.print ("Enter the length of your box: ");
// read this input
userInputLength = (reader.nextDouble());
// ask the user for input
System.out.print ("Enter the width of your box: ");
// read this input
userInputWidth = (reader.nextDouble());
// ask the user for input
System.out.print ("Enter the height of your box: ");
// read this input
userInputHeight = (reader.nextDouble());
Block blockOne = new Block(name, userInputLength, userInputWidth, userInputHeight);
System.out.println( blockOne.showBoxAsString());
My object
package model;
import java.util.ArrayList;
import java.util.List;
public class Block {
// name variable of the figure
private String name;
// dimension variable of the figure
private double blockWidth;
private double blockHeight;
private double blockLength;
public Block() {
}
// form a block
public Block(String N, double L, double W, double H){
this.name = N;
this.blockLength = L;
this.blockWidth = W;
this.blockHeight = H;
}
// set the name
public void setBlockName(String N){ this.name = N; }
// set the name
public String getBlockName(){ return this.name; }
//set length method
public void setLength(double L)
{
this.blockLength = L;
}
//get length method
public double getLenght(){
return this.blockLength;
}
//set width method
public void setWidth(double W)
{
this.blockLength = W;
}
//get width method
public double getWidth(){
return this.blockWidth;
}
//set height method
public void setHeight(double H)
{
this.blockLength = H;
}
//get height method
public double getHeight(){
return this.blockHeight;
}
// method to calculate the surface of the shape (in this situation its a box)
public double calcSurfaceBox(){
// the formula to calculate the surface of the box is length times the width
double surface = 2 * (this.blockHeight * this.blockWidth) +
2 * (this.blockLength * this.blockHeight) +
2 * (this.blockWidth * this.blockLength) ;
// return the calculated value of surface
return surface;
}
// method to calculate the volume of the shape (in this situation it's a box)
public double calcVolumeBox(){
// the formula to calculate the volume is length times width times height
double volume = this.blockLength * this.blockWidth * this.blockHeight;
// return the calculated value of volume
return volume;
}
// a method to print a string to show the user the size of the shape (in this case a box.)
public String showBoxAsString(){
return String.format( "The box has a name: " + getBlockName() + "\n" +
"The box has a Length of: " + getLenght() + "\n" +
"The box has a Width of: " + getWidth() + "\n" +
"The height of the box is: " + getHeight());
}
}
i searched for multiple solutions but i can't figure it out. Is there anyone that could give me some tools or an idea?
my goal is to make my main code as clean as possible. so if anyone got an idea how i can simplify my main code that would be awesome.

Initialise an array of Block Objects
Block blocks[] = new Block[length];
To access each object use blocks[index]
Note: The array elements here store the reference variables to the object
Edit: index here means a block object perhaps blockOne

Related

How to get JOptionPane to calculate area?

I have created this code, the GUI pops up and works perfectly, but the area is not being calculated correctly. Any Clue why? I am very new to Java coding, so any help is appreciated. Thanks in advance.
package pkg4.pkg2.pkgnew.project;
import javax.swing.JOptionPane;
public class NewProject {
public static void main(String[] args) {
String inputStr = JOptionPane.showInputDialog("Type 1 for the area of Triangle, 2 for area of Circle, 3 for Rectangle, and 0 for area of none of these.");
int i = Integer.parseInt(inputStr);
if (i == 1) {
String input = JOptionPane.showInputDialog("Enter the first value to calculate the area of a triangle: ");
int n1 = Integer.parseInt(inputStr);
String inp = JOptionPane.showInputDialog("Enter the second value to calculate the area of a triangle: ");
int n2 = Integer.parseInt(inputStr);
areaTriangle(n1, n2);
}
if (i == 2) {
String inpu = JOptionPane.showInputDialog("Enter a value to calculate the area of a circle: ");
double radius = Integer.parseInt(inputStr);
areaCircle(radius);
}
if (i == 3) {
String inp = JOptionPane.showInputDialog("Enter the first value to calculate the area of a rectangle: ");
int m1 = Integer.parseInt(inputStr);
String inp2 = JOptionPane.showInputDialog("Enter the second value to calculate the area of a rectangle: ");
int m2 = Integer.parseInt(inputStr);
areaRectangle(m1, m2);
} else {
return;
}
}
public static void areaTriangle(int n1, int n2) {
int areat = (n1 * n2) / 2;
JOptionPane.showMessageDialog(null, "The area of a triangle with your values is: " + areat);
}
public static void areaCircle(double radius) {
double areac = Math.PI * (radius * radius);
JOptionPane.showMessageDialog(null, "The area of a circle with your value is: " + areac);
}
public static void areaRectangle(int m1, int m2) {
int arear = (m1 * m2);
JOptionPane.showMessageDialog(null, "The area of a rectangle with your values is: " + arear);
}
public static void calcArea(int x) {
}
}
The problem with your code is that every time you parse the input into a string you are always using the same value of the string. Everytime you call your functions you are using all 1, 2, or 3 for your parameters into your area function calls. So you need to change the Integer.parseInt() to contain the new strings you get from the user like so:
String input = JOptionPane.showInputDialog("Enter the first value to calculate the area of a triangle: ");
int n1 = Integer.parseInt(input); //not inputStr <----------
String inp = JOptionPane.showInputDialog("Enter the second value to calculate the area of a triangle: ");
int n2 = Integer.parseInt(inp);//not inputStr <---------
areaTriangle(n1, n2);

non-static variable cannot be referenced from a static context in println statement

I know that these types of questions get asked a lot and I've read
this one
and
this one
but for some reason I'm still having troubles understand the issue my current program is having.
I'm trying to create a set of classes that defines a series of 3-D shapes that can store its size, and provides access to change the data. It should also be able to calculate circumference, area, and volume. I've only gotten to the point where I'm doing my first chosen shape (a sphere) and I'm getting this error in the println inside the if statement.
import java.util.Scanner;
public class Shapes
{
public static void main(String[] args)
{
String input;
double Radius;
Scanner scan = new Scanner(System.in);
System.out.println("Choose a shape. 'S' for sphere, 'P' for pyramid, 'C' for cone: ");
input = scan.next();
if (input.equals("S"))
{
System.out.println("Enter radius: ");
Radius = scan.nextDouble();
Sphere calcCircumference;
Sphere calcArea;
Sphere calcVolume;
System.out.println("The circumference is "+Sphere.circumference+", the area is "+Sphere.area+", the volume is "+Sphere.volume+".");
}
}
}
public class Sphere
{
// instance variables
protected double radius;
protected double circumference;
protected double area;
protected double volume;
Scanner scan = new Scanner(System.in);
/**
* Constructor for objects of class Sphere
*/
public Sphere()
{
// initialise instance variables
radius = 0;
circumference = 0;
area = 0;
volume = 0;
}
/**
*Gets user entered radius
*/
public double getRadius(double Radius)
{
radius = radius;
return radius;
}
public double calcCircumference()
{
circumference = 2*Math.PI*radius;
return circumference;
}
public double calcArea()
{
area = 4*Math.PI*Math.pow(radius,2);
return area;
}
public double calcVolume()
{
volume = (4*Math.PI*Math.pow(radius,3))/3;
return volume;
}
}
Any help or guidance would be appreciated.
System.out.println("The circumference is "+Sphere.circumference+", the area is "+Sphere.area+", the volume is "+Sphere.volume+".");
You need to create an instance of Sphere before you can access it fields.
Sphere sphere = new Sphere();
You then need to provide the information that the object needs
sphere.radius = Radius; // I'd prefer a setter method
Then you can make use of the information that this instance provides...
System.out.println("The circumference is "+sphere.calcCircumference()+", the area is "+Sphere.calcArea()+", the volume is "+Sphere.calcVolume()+".");
There is no need to keep track of circumference, area or volume, they are calculated fields, you simply need to call the methods you need to get the calculated result.
The fields circumference, area, volume and radius are known as instance fields, they require an instance of the class before you can use them. This means you can have multiple instances of Sphere each with there own unquie values
You might like to take a closer look at Classes and Objects
I changed your code a bit, now it is working (may not be the most efficient way):
import java.util.Scanner;
public class Shapes {
public static void main(String[] args) {
String input;
double Radius;
Scanner scan = new Scanner(System.in);
System.out
.println("Choose a shape. 'S' for sphere, 'P' for pyramid, 'C' for cone: ");
input = scan.next();
if (input.equals("S")) {
System.out.println("Enter radius: ");
Radius = scan.nextDouble();
Sphere calcCircumference;
Sphere calcArea;
Sphere calcVolume;
System.out.println("The circumference is " + Sphere.circumference
+ ", the area is " + Sphere.area + ", the volume is "
+ Sphere.volume + ".");
}
}
public static class Sphere {
// instance variables
protected double radius;
protected static double circumference;
protected static double area;
protected static double volume;
Scanner scan = new Scanner(System.in);
/**
* Constructor for objects of class Sphere
*/
public Sphere() {
// initialise instance variables
radius = 0;
circumference = 0;
area = 0;
volume = 0;
}
/**
* Gets user entered radius
*/
public double getRadius(double Radius) {
radius = radius;
return radius;
}
public double calcCircumference() {
circumference = 2 * Math.PI * radius;
return circumference;
}
public double calcArea() {
area = 4 * Math.PI * Math.pow(radius, 2);
return area;
}
public double calcVolume() {
volume = (4 * Math.PI * Math.pow(radius, 3)) / 3;
return volume;
}
}
}

Using toString correctly

I am working on some home work and cannot figure out how to call the toString methods from the Point, Square and Cube classes to print out. I know it has to be something stupid, I think I am just toast and my mind is spent. Right now I have ??? in place where the toSting methods should go. Have tried every combination ("class".toString, etc) I can think of. Can anyone tell me where I am messing up? Thanks!!
import javax.swing.JOptionPane;
public class InheritanceTest {
public static void main(String args[]){
// Declare variables
String xString = null;
String yString = null;
String sideString = null;
int x = 0;
int y = 0;
int sideLength = 0;
try{
xString = JOptionPane.showInputDialog("Enter x coordinate:");
x = Integer.parseInt(xString);
yString = JOptionPane.showInputDialog("Enter y coordinate:");
y = Integer.parseInt(yString);
sideString = JOptionPane.showInputDialog("Enter side of Square:");
sideLength = Integer.parseInt(sideString);
} // End try
catch(NumberFormatException e){
JOptionPane.showMessageDialog( null,"The value you entered is not a valid number. Please try again",
"Error", JOptionPane.ERROR_MESSAGE);
} // End catch
JOptionPane.showMessageDialog(null, "Point: \n" +????????, "Results", JOptionPane.INFORMATION_MESSAGE);
} // End main
}// End Class
class Point{
//Declare variables
private int x;
private int y;
// Point constructor
Point(int xCoordinate,int yCoordinate){
x = xCoordinate;
y = yCoordinate;
}// End Point Constructor
// Accessor to return x coordinate
public int getX(){
return x;
}// End getX method
// Accessor to return y coordinate
public int getY(){
return y;
}// End getY method
// Format and display coordinates
public String toString(){
return "Corner = [" + x + "," + y + "]\n";
}// End toString
}// End Point Class
abstract class Square extends Point{
//Declare variables
private double sideLength;
// Square constructor
Square(int x, int y, double s){
super(x, y);
sideLength = s;
} // End Square constructor
// Accessor to return side length
public double getSide(){
return sideLength;
} // End getSide
// Method to calculate area of square
public double area(){
return sideLength * sideLength;
} // End area method
// Method to calculate perimeter of square
public double perimeter(){
return 4 * sideLength;
} // End perimeter method
// Format and display the square
public String toString(){
return super.toString() + "Side length is: " + sideLength + "\n" +
"Area is: " + area() + "\n" + "Perimeter is: " + perimeter();
} // End toString
}// End Square Class
abstract class Cube extends Square{
// Declare variable
double depth;
// Cube constructor
public Cube(int x, int y, double s, double z){
super(x, y, s);
depth = z;
} // End Cube constructor
// Method to calculate area of cube
public double area(){
return 6 * super.area();
} // End Area
// Method to calculate volume of cube
public double volume(){
return super.area() * depth;
} // End volume
// Format and display the cube
public String toString(){
return "Depth is: " + depth + "\n" + "Area is: " + area() + "\n" + "Volume is: " + volume();
} // End toString
} // End Cube class
You don't invoke the toString() method from a Class, you invoke it from an object (i.e. an instance of that Class). It's obj.toString() where obj is an instance of Point, Square or Cube (or any other class).
I don't see you instantiating any objects of those classes, though. You need to create an instance of the class before you can invoke an instance-based method like toString().
Point myPoint = new Point(x, y);
String pointString = myPoint.toString();
Well you need to create an instance of the class that you want to work with first, for example:
Square s = new Square(10, 10, 2.0);
System.out.println(s.toString());
new Point(x,y).toString()
toString() is a method of the Point class. You need to instantiate it first with x and y coordinates then call its toString() method.
JOptionPane.showMessageDialog(null,
"Point: \n" + new Point(x, y).toString,
"Results",
JOptionPane.INFORMATION_MESSAGE);

Calculating perimeter and area of a rectangle

I need to be able to input length and width of a rectangle into a console and calculate its perimeter and area. I have it working other than accepting my inputs for the calculations. I know I'm close, but can't seem to figure it out. Thanks in advance for your help. Keep in mind I'm a novice to put it nicely, so your answers may not make sense to me at first. I cannot get it to calculate the values that I input into the console.
package edu.purdue.cnit325_lab1;
public class Rectangle {
private static double length;
private static double width;
public Rectangle() {
length=0.0;
width=0.0;
}
public Rectangle(double l, double w) {
length = l;
width = w;
}
public double FindArea() {
return length*width;
}
public double FindPerim() {
return length*2 + width*2;
}
}
package edu.purdue.cnit325_lab1;
import java.util.Scanner;
public class TestRectangle {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanL = new Scanner (System.in);
System.out.print("Please enter the length of the rectangle: ");
double L = scanL.nextDouble();
Scanner scanW = new Scanner (System.in);
System.out.print("Please enter the length of the rectangle: ");
double W = scanW.nextDouble();
//int W = scanW.nextInt();
double RectangleArea;
Rectangle unitRectangle = new Rectangle();
RectangleArea = unitRectangle.FindArea();
System.out.println("The area of a unit rectangle is " + RectangleArea);
double RectanglePermiter;
Rectangle perimRectangle = new Rectangle();
RectanglePermiter = perimRectangle.FindPerim();
System.out.println("The permimiter of the unit rectangle is " + RectanglePermiter);
}
}
Note that you are calling the Rectangle constructore with no arguments thus setting its width and height to zero, you should use
Rectangle unitRectangle = new Rectangle(L,W);
and indeed like the other answer you should use one Scanner instance.
Plus regarding coding style: do not upercase your variable names. Its quite confusing for more "experienced" java developers. :-)
you missed to call parameterized constructor.
public static void main(String[] args) {
Scanner scanL = new Scanner (System.in);
System.out.print("Please enter the length of the rectangle: ");
double L = scanL.nextDouble();
System.out.print("Please enter the length of the rectangle: ");
double W = scanL.nextDouble();
Rectangle rectangle = new Rectangle(l,w);
double rectangleArea = rectangle .FindArea();
System.out.println("The area of a unit rectangle is " + rectangleArea);
double rectanglePermiter = rectangle.FindPerim();
System.out.println("The permimiter of the unit rectangle is " + rectanglePermiter);
}
Note: Unnecessarily you created two Scanner objects and two Rectangle objects in your code,which are removed from the above code.
Use one Scanner instance. Just reuse it.
Scanner scanner = new Scanner (System.in);
System.out.print("Please enter the length of the rectangle: ");
double L = scanner.nextDouble();
System.out.print("Please enter the length of the rectangle: ");
double W = scanner.nextDouble();
Update: You don't pass the L and W to the constructor as the other answer points out. However, some mistakes you made:
You declared length and width as static. Don't do that. That makes no sense. The length and the width are properties of a rectangle and shouldn't be shared by all rectangle instances.
You don't use the correct naming conventions: variables start with a lowercase character, class names start with an uppercase character.
You are creating two instances of your Rectangle to calculate both perimeter and area of the same rectangle. Share that instance instead.
So you need to set the values in some way... you can do either
A)
Rectangle unitRectangle = new Rectangle(l,w);
B)
or create getters and setters in the rectangle class..
setLength(double l) length = l;
setWidth(double w) width = w
double getLength() return length;
double getWidth() return height;
Since you are initializing with the default constructor
aka
Rectangle unitRectangle = new Rectangle();
the values for length and width will also be zero.
Your code consists of the Default constructor, which will initialize the respective values length and width to 0.0 as set by you and also consist of parametrized constructor which requires input values to be provided and will set the value accordingly.
When you are creating the object of your class, you are calling the Default Constructor instead of parametrized constructor in this line
Rectangle unitRectangle = new Rectangle();
Thus setting them to 0.0
If you do Something like this
Rectangle unitRectangle2 = new Rectangle(2.3,4.3);
This will create the object having values for length and breadth as 2.3 and 4.3 respectively.
//write a java program which will calculate area and perimeter of rectangle by accepting radius from cmd prompt
//area = width x height,perimeter = (2 x width) + (2 x height)
class AreaAndPerOfRect
{
int h,w;
void set(int x,int y)
{
h=x;
w=y;
}
int AreaOfRect()
{
int area=w*h;
return area;
}
int PerOfRect()
{
int per=(2*w)+(2*h);
return per;
}
void disp()
{
int area=AreaOfRect();
System.out.println("area of rectangle"+area);
int per=PerOfRect();
System.out.println("area of rectangle"+per);
}
}
class AreaAndPerOfRectDemo
{
public static void main(String args[])
{
if(args.length!=2)
{
System.out.println("please enter two values");
}
else
{
int x=Integer.parseInt(args[0]);
int y=Integer.parseInt(args[1]);
AreaAndPerOfRect ap=new AreaAndPerOfRect();
ap.set(x,y);
ap.disp();
}
}
}
//This is the Java code for finding the area and perimeter of a rectangle
package demo;
import java.util.Scanner;
public class DemoTranslation {
public static int area(int length, int width) {
int areaOfRectangle;
areaOfRectangle = length * width;
System.out.println("Area of Rectangle is : " + areaOfRectangle);
return 0;
}
public static int perimeter(int length, int width) {
int perimeterOfRectangle;
perimeterOfRectangle = (length + width) * 2;
System.out.println("Perimeter of Rectangle is : " + perimeterOfRectangle);
return 0;
}
public static void main(String[] args) {
int length, width, choice;
System.out.println("Enter the length of the triangle ");
length = STDIN_SCANNER.nextInt();
System.out.println("Enter the width of the triangle ");
width = STDIN_SCANNER.nextInt();
System.out.println("Enter 1 : View the area ");
System.out.println("Enter 2 : View the perimeter ");
System.out.println("Enter 3 : view both ");
choice = STDIN_SCANNER.nextInt();
switch(choice) {
case 1:
area(length, width);
break;
case 2:
perimeter(length, width);
break;
case 3:
area(length, width);
perimeter(length, width);
break;
default:
System.out.println("Invalid option ");
break;
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

Function isn't calculating correctly?

After creating three objects it is supposed to take the radius and height from the user, calculate the volume and then ask again for the next cylinder. When I run this code it does prompt me for the radius and height, but it does not calculate the volume. What am I doing wrong?
import javax.swing.JOptionPane;
import java.io.*;
public class CylinderTest
{
public static void main(String[] args) throws IOException
{
String input;
String input2;
double radius[] = new double[3];
double height[] = new double[3];
Cylinder[] myCylinder = new Cylinder[3];
for (int i = 0; i < myCylinder.length; i++)
{
input = JOptionPane.showInputDialog("Enter a radius");
radius[ i ] = Double.parseDouble(input);
input2 = JOptionPane.showInputDialog("Enter a height" +
"");
height[i] = Double.parseDouble(input2);
myCylinder[i].height = input2;
myCylinder[i].radius = input;
JOptionPane.showMessageDialog(null, " The volume of the cylinder is: " + myCylinder.getVolume());
}
}
static class Cylinder
{
private double radius;
private double height;
public Cylinder(double radius, double height)
{ this.radius = radius;
this.height = height;
}
public double getVolume()
{
return radius * radius * height * Math.PI;
}
}
}
You are using the keyword static for your variables and methods inside your Cylinder class. I'm not sure why you did use the static keyword, but static implies there will be only one instance for the whole program (i.e. it is a global variable or function) . To fix it, delete the word static in the Cylinder class's methods and member variables. You may also want to look at Math.PI instead of using 3.1416 as PI.
Also, thought I'd mention, that you don't need to store the volume in a variable. Instead, you can simply return it. Unless of course you want to cache it in a variable for some reason, but seeing as you're recalculating it every call to getVolume(), there is no need to store the volume in a variable.
i.e.
public double getVolume() // notice: no static keyword in the method's prototype
{
return (radius * radius) * height * Math.PI;
}
Pro tip: Don't use magic numbers in your code, use a variable to store the magic number. As a constant (final) variable or a regular one.
e.g.
static final int MEANING_OF_LIFE = 42; // this is somewhere tucked in a class or method
// static is used because the final keyword
// is used and therefore isn't modified
// Meaning that there is no real point to have
// multiple MEANING_OF_LIFE variables, hence static
// ...
System.out.printf("The meaning of life is: %i", MEANING_OF_LIFE);
You forgot
myCylinder[i].height = input2;
myCylinder[i].radius = input;
Plus,
JOptionPane.showMessageDialog(null, " The volume of the cylinder is: " + myCylinder.getVolume());
remove the static from getVolume(). remove the static from fields volume, height.
To calculate you have to create a cylinder object, and get the volume:
Cylinder cyl = new Cylinder(radius, height);
double volume = cyl.getVolume();

Categories

Resources