How to get Anonym Objects parameters? - java

Im trying to add my anonymous objects from a class to a Hashtable. I created my Hashtable as my teacher wants but there is one problem. I have to get x and y values one of my Objects. But System cannot find x anyway.
public class HashDatastructure{
public static void main(String[] args){
java.util.Hashtable kreise = new java.util.Hashtable();
for(int i = 0; i < 6; i++){
kreise.put(new Integer(i), new Kreis(120, 120, 60));
}
System.out.println(kreise.get(3).toString() + " is 4. Object
and this Object's X Value: "
+ kreise.get(3).x + " || Y Value: ");
}
}
And here it is my Kreis Class:
public class Kreis extends Object{
public int x; //Mittelpunkt-x
public int y; // Mittelpunkt-y
public int radius;
public final double PI = 3.14159; //Constant Variable for pi
public static int kreisCounter = kreisZaehler();
public static int counter = 0;
public Kreis(int x, int y, int radius){
this.x = x;
this.y = y;
this.radius = radius;
kreisCounter();
}
private static int kreisZaehler(){
counter++;
return counter;
}
public void setRadius(int wert){
radius = wert;
}
public double getFlaeche(){
return radius * radius * PI;
}
public double getUmfang(){
return 2 * radius * PI;
}
}

I don't know what you mean by "anonymous objects," but you're using raw types, which is generally not a good idea. Instead, tell the compiler what kind of object kreis contains:
java.util.Hashtable<Kreise> kreise = new java.util.Hashtable<>();
// ----------------^^^^^^^^---------------------------------^^
Then, the compiler will know that get returns a Kreis object, which has x and such. (Side note: Probably better to make x private and provide an accessor like getX for it.)
More to explore in the Generics Java Tutorial.
If for some reason you have to use raw types, you can cast to Kreis on retrieval:
// NOT recommended
System.out.println(kreise.get(3).toString() + " is 4. Object and this Object's X Value: "
+ (((Kreise)kreise.get(3)).getX() + " || Y Value: ");
// -----------------^^^^^^^^^-------------^-^^^^^^
(Note I'm assuming you make x private and provide an accessor for it.)

Related

In Java how should I command a 2D point to move along the vector line of distance to another point?

I have a simple class 2Dpoints with two fields, x and y. I want to write a code so that I could command one point to moves slowly to another point, like so that it moves on the vector line of their distances. But I don't know how?
I've first thought  that it should contain a for loop so that it would know, it should move till it reaches the other point
something like for(int d=0 ; d<distance ; d++) but I don't know how should I then command it so that it would move on the line?
import java.lang.Math.*;
public class Punkt {
private int x;
private int y;
public Punkt(int x, int y) {
this.x=x;
this.y=y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void setX(int distance) {
x = x + distance;
}
public void setY(int distance) {
y = y + distance;
}
public void moveAbout(int dx, int dy) {
x = x + dx;
y = y + dy;
}
/// method for calculating the distance to another point
public double giveDistance(Punkt otherPoint) {
return Math.sqrt(
(otherPoint.getY() - y) *
(otherPoint.getY() - y) +
(otherPoint.getX() - x) *
(otherPoint.getX() - x));
}
}
I've commented the major lines:
import static java.lang.Math.*;
/**
* Immutable structure. Functional way
*/
class Point {
public final double x;
public final double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
/**
* Here you are. This is what you want to implement.
* from.moveTo(0.0, to) => from
* from.moveTo(1.0, to) => to
*
* #param by - from 0.0 to 1.0 (from 0% to 100%)
* #param target - move toward target by delta
*/
public Point moveTo(double by, Point target) {
Point delta = target.sub(this);
return add(delta.dot(by));
}
public Point add(Point point) {
return new Point(x + point.x, y + point.y);
}
public Point sub(Point point) {
return new Point(x - point.x, y - point.y);
}
public Point dot(double v) {
return new Point(v * x, v * y);
}
public double dist(Point point) {
return sub(point).len();
}
public double len() {
return sqrt(x * x + y * y);
}
public String toString() {
return x + ":" + y;
}
}
class Main {
public static void main(String[] args) {
Point source = new Point(2, 3);
Point target = new Point(-4, 9);
// You can utilize the cycle or implement kind of timer to animate something
for (int t = 0; t <= 100; t++) {
System.out.println(source.moveTo(0.01 * t, target));
}
}
}
https://replit.com/join/sucvdhpqoa-redneckz
#AlexanderAlexandrov I've change the type of my variables to double accordingly, now in one of my classes I have a method givePoints, which uses Scanner for asking a user how many points he wants and what are the coordinates then it saves them into an array of points with first element being always(0,0).
Another method takes an array of points as parameter and sort them in order of their distances to point(0,0).
These methods work perfectly. The problem is with method hitThepoints.
Here I want to first create the array of points, sort them, and then command my robot to hit all the points. robot is an object of class Robot extends circle, with position of type Point, that at first is at point(0,0)
public void hitThePoints(){
Point[] poi=sortPoints (givePoints()); //Creates a sorted array of points
Point short=new Point(poi[1].getX(),poi[1].getY());
System.out.println(" the nearest point is :");
System.out.println("("+short.getX()+ ","+short.getY()+")");
for(int i=1; i<poi.length;i++){
Point source=robot.position;
Point target=new Point(poi[i].getX(), poi[i].getY());
while(source.getX()!=target.getX() &&
source.getY()!=target.getY()){
robot.bewegeUm((source.moveTo(0.01,target)).getX(),
(source.moveTo(0.01,target)).getY());
if(source.getX()!=target.getX() &&
source.getY()!=target.getY()){break;}
System.out.println(source.getX() +","+ source.getY());
}
}
}

Anything declared in a method of Java is local (except in some special cases), is that right?

public class Triangle {
double area;
int height;
int length;
public static void main(String [] args) {
int x = 0;
Triangle [ ] ta = new Triangle[4];
while ( x < 4 ) {
ta[x] = new Triangle();
ta[x].height = (x + 1) * 2;
ta[x].length = x + 4;
ta[x].setArea();
System.out.print("triangle "+x+", area");
System.out.println(" = " + ta[x].area);
x = x + 1;
}
int y = x;
x = 27;
Triangle t5 = ta[2];
ta[2].area = 343;
System.out.print("y = " + y);
System.out.println(", t5 area = "+ t5.area);
}
void setArea() {
ta[x].area = (height * length) / 2;
}
}
$javac Triangle.java
Triangle.java:25: error: cannot find symbol
ta[x].area = (height * length) / 2;
^
symbol: variable ta
location: class Triangle
Triangle.java:25: error: cannot find symbol
ta[x].area = (height * length) / 2;
^
symbol: variable x
location: class Triangle
2 errors
Of course I soon find that I need to take "ta[x]." thing off the setArea method, that's clear, but now I'm wondering why I cannot put a previously-declared Triangle array before that area function.
Is it because within the method, all things are local and you can't use variables which aren't declared in that method even if you've already declared them in other parts of code? Thank you guys.
x ta are local variable their scope are limited their respective function outside the scope you can not reference it.
Just pass the reference.
public class Triangle {
double area;
int height;
int length;
public static void main(String [] args) {
int x = 0;
Triangle [ ] ta = new Triangle[4];
while ( x < 4 ) {
ta[x] = new Triangle();
ta[x].height = (x + 1) * 2;
ta[x].length = x + 4;
ta[x].setArea(ta[x]);
System.out.print("triangle "+x+", area");
System.out.println(" = " + ta[x].area);
x = x + 1;
}
int y = x;
x = 27;
Triangle t5 = ta[2];
ta[2].area = 343;
System.out.print("y = " + y);
System.out.println(", t5 area = "+ t5.area);
}
void setArea(Triangle t) {
t.area = (height * length) / 2;
}
}
ta,x variable scope limited to Main() funtion
The question you have asked is related to the concept of scope of a variable in java.
Any variable declared inside {}, can be accessible inside those{} only. Outside the {},variables are not accessible.
In your code area is instance variable of class Triangle having length and height as instance variables.
So to calculate area you can directly use length and height. like
area=length*height
To calculate the area of perticular object call it through that object or you can pass triangle object as mentioned in previous post posted by user207421
You have couple of the problems in the snippet. Let me show you:
It's better to use immutable objects whenever it's possible. Imagine if someone will use your Triangle and forget to invoke setArea();
One of OOP's principles is encapsulation, so you should avoid access to the class's variables directly (only with getters);
In general, you should store minimum information. E.g. setArea() should be moved directly to the Triangle class. Moreover, it's pretty simple to calculate and it's better to do it
And finally look at division operation; before doing / you have to cast the result to the double. If you do (int + int) / int - the result will always be an integer.
Please check my solution:
// class is final (this is not mandatory)
public final class Triangle {
// variables are final (in general this is good approach)
// variables are private (access only via getters)
private final int width;
private final int height;
public Triangle(int width, int height) {
this.width = width;
this.height = height;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
// 2.0 is very important, here we cast (width * height) to double before division
public double getArea() {
return (width * height) / 2.0;
}
}
public class Main {
public static void main(String... args) {
Triangle[] triangles = createTriangles(4);
print(triangles);
}
private static Triangle[] createTriangles(int total) {
Triangle[] triangles = new Triangle[total];
// for loops letters like i,j,k are more common (x is mostly to 2D)
for (int i = 0; i < triangles.length; i++) {
int width = i + 4;
int height = (i + 1) * 2;
triangles[i] = new Triangle(width, height);
}
return triangles;
}
private static void print(Triangle... triangles) {
if (triangles != null)
for (int i = 0; i < triangles.length; i++)
System.out.format(Locale.ENGLISH, "triangle %d, area = %.2f",
i, triangles[i].getArea());
}
}
The setArea() mehtod is part of the class triangle,so there is no issue in calculating area of a trisngle.
public class Triangle {
double area;
int height;
int length;
public double setArea(){
return area=(length*height)/2;
}
public static void main(String[] args) {
int x=0;
Triangle [ ] ta = new Triangle[4];
while ( x < 4 ) {
ta[x] = new Triangle();
ta[x].height = (x + 1) * 2;
ta[x].length = x + 4;
ta[x].setArea();
System.out.print("triangle "+x+", area");
System.out.println(" = " + ta[x].area);
x = x + 1;
}
int y = x;
x = 27;
Triangle t5 = ta[2];
ta[2].area = 343;
System.out.print("y = " + y);
System.out.println(", t5 area = "+ t5.area);
}
}

Center for Regular Polygon Code

I am trying to write a code that follows certain criteria regarding Regular Polygons and finding the perimeter and area of the polygon. I have to write three different classes Point2D, RegularPolygon, and Driver. I can get all of the necessary criteria to work fine except for when it comes to using the instance variable center to have the center coordinates x and y. There are two things that use the center in the RegularPolygon code and I can't get them to work. I need to have a Point2D instance variable center that stores the x and y coordinates of the polygon’s center, with default values 0 for both the x and y components of the Point2D object. I also need to have a constructor that creates a regular polygon with the specified number of sides, length of side, and a Point2D object that represents the center of the polygon, in that order. I also need to have A method public String toString()that returns a String representation of the polygon containing the number of sides, side length and center coordinates for this polygon. Call the toString()method on the Point2Dcenter as part of this method. However, when I go to call the toString method in Point2D it comes up as an error. If anyone can help me figure out why I can't get it to work in my code I would greatly appreciate it.
//Code for Point2D
public class Point2D
{
//Instance Variables
private int x;
private int y;
/**
* Constructor for objects of class Point2D, this will initialize
* the instance variables
*/
public Point2D(int xVariable, int yVariable)
{
//Initializes Instance Variables
x = xVariable;
y = yVariable;
}
//Accessor Method for X variable
public int getX() {
return x;
}
//Accessor Method for X variable
public int getY() {
return y;
}
//ToString Method
public String toString() {
return "<" + x + "," + y + ">";
}
//Method that tests if the values of x and y are equal
public boolean equal(Object o) {
if (o instanceof Point2D) {
Point2D c = (Point2D)o;
}
return false;
}
}
//Code for RegularPolygon
public class RegularPolygon
{
// instance variables
private int n; //Number of sides
private double side; //Length of sides
private double x; //Value of X-Coordinate
private double y; //Value of y-Coordinate
private double center;
/**
* No argument constuctor that creates a regular polygon with
* default values
*/
public RegularPolygon()
{
//Intilializes Instance Variables
n=3;
side =1;
x=0;
y=0;
}
/**
* Constructor that creates a regular polygon with a specific number
* of sides, length of side, and a Point2D object that represents the
* center of the polygon.
*/
public RegularPolygon(int n, double side, double x, double y) {
this.n = n;
this.side= side;
this.x = 0;
this.y = 0;
}
//Mututator Methods
public void setN(int nValue) {
n = nValue;
}
public void setSide(double sideValue) {
side = sideValue;
}
public void setX(double xValue) {
x = xValue;
}
public void setY(double yValue) {
y = yValue;
}
//Accessor Methods
public int getN() {
return n;
}
public double getSide() {
return side;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
//Calculates the Perimeter of the regular polygon
public double getPerimeter() {
return n * side;
}
//Calculates the Area of the regular polygon
public double getArea() {
double area = (n * (Math.pow(side,2))) / (4 * (Math.tan(Math.PI/n)));
return area;
}
//To String Method
public String toString() {
return "Number of sides: " + n + ", Side Length: " + side + ", Center Coordinates: "+Point2D.toString(x,y);
}
}
Your toString method in Point2D does not take variables as parameters, yet you call it from RegularPolygon with parameters at the end. But the way you called Point2D uses its toString method like a static method, even though it's not. So you either have to instantiate a Point2D, or make Point2D's toString method static. But the problem with this is that then you have to make your x and y in Point2D static as well. Another problem with making your toString() method static is that you can't override Object's toString method. So I recommend that you do the following:
public String toString() {
return "Number of sides: " + n + ", Side Length: " + side + ", Center Coordinates: "+new Point2D((int)x, (int)y).toString();
}

Creating a method that accepts an array of interface objects

So, I have a twoparter question. The first part I did, which was creating an interface and then utilizing that interface in two different classes. However the second part of the question has me stumped. I'm not understanding the logic aspect of it. It feels as though the question order should be in reverse. This is two things I need to do to finish up the last portion of the assignment. If anyone here could give me just some tiny guidance as to to the direction I should be taking I'd greatly appreciate it.
Part II:
(1)Create an array of Calculatable objects in main and call the sumCalculate method.
For the most part I understand this, I already began doing it but decided to start working on (2) since that was way more difficult for me. It's basically creating an array of Calculatable objects of a certain size ( I chose 5) and populating it with different calculatable objects ( could be rectangles or squares in my example). But the second half of this question confuses me? Am I calling the sumCalculate method that I'm GOING to be making in question 2? Or am I calling it before I even make the (2) method.
(2)Make a method that accepts an array of Calculatable objects and sums up the values that are returned by each object's call to calculate.
What I'm trying to figure out here in question (2) is this. When it asks me to make the method? Does this mean that I'm making a new method in interface called sumCalc for example, that has parameters that accepts an array of calculatable objects? And then as far as summing up the values that are returned. I'd assume that I'd be adding the calculation double that is returned by calculate methods.
I'd ask my professor but this professor I decided to take has made it a habit of being excessively difficult to reach. Sorry to bother you guys with what is most likely an elementary and not difficult question.
interface Calculatable {
public double calculate(int x);
}
class square implements Calculatable {
public double side;
square(double side){
this.side = side;
}
public double getside(){
return side;
}
public double calculate(int x) {
double perimeter = side * 4;
System.out.println("This calculate method will output the perimeter divided by the parameter x");
double calculation = perimeter / x;
System.out.println("The original perimeter was " + perimeter + ". And the calculated perimeter is " + calculation +".");
return calculation;
}
}
public class rectangle implements Calculatable {
public double length;
public double width;
rectangle(double length , double width){
this.length = length;
this.width = width;
}
public double getlength(){
return length;
}
public double getwidth(){
return width;
}
public double calculate(int x) {
double perimeter = 2 * (length + width);
double calculation = 2 * perimeter;
System.out.println("This will return the perimeter of the rectangle times the x paramater");
System.out.println("Your current perimeter is " + perimeter + " and your perimeter after the calculation is " + calculation + ".");
return calculation;
}
public static void main(String [] args){
Calculatable perimeter1 = new rectangle(20.5 , 50);
perimeter1.calculate(5);
Calculatable perimeter2 = new square(10.5);
perimeter2.calculate(2);
Calculatable[] perimetersums = new Calculatable[5];
perimetersums[0] = new rectangle(20.5 , 50);
perimetersums[1] = new rectangle(10 , 25);
}
}
I would create sumCalculate beside main method and be over with it. Lesson is to implement an interface method and use it too.
And beside that I suggest reading Java naming convention and correcting your code accordingly.
The way I understand it you should not change the Interface, especially if the Interface was provided to you!
Just write your sumCalculate below your main method like this
private static double sumCalculate(Calculateable[] c) {
// do your sum up and return the result
}
and call it in your main method like this
double sum = sumCalculate(perimetersums);
few confusion is in my mind.. In the implementation rectangle your are not using the x in the calculate method. I changed the whole class structure a little bit.. Please look.. I think it will help you...
public interface Calculatable {
public double calculate(int x);
public double getPerimeter();
}
public class square implements Calculatable {
public double side;
private double perimeter;
square(double side){
this.side = side;
}
public double getside(){
return side;
}
public double calculate(int x) {
double perimeter = side * 4;
System.out.println("This calculate method will output the perimeter divided by the parameter x");
double calculation = perimeter / x;
System.out.println("The original perimeter was " + perimeter + ". And the calculated perimeter is " + calculation +".");
this.perimeter=calculation;
return calculation;
}
#Override
public double getPerimeter() {
// TODO Auto-generated method stub
return perimeter;
}
}
public class rectangle implements Calculatable {
public double length;
public double width;
private double perimeter;
rectangle(double length , double width){
this.length = length;
this.width = width;
}
public double getlength(){
return length;
}
public double getwidth(){
return width;
}
public double calculate(int x) {
double perimeter = 2 * (length + width);
double calculation = 2 * perimeter;
System.out.println("This will return the perimeter of the rectangle times the x paramater");
System.out.println("Your current perimeter is " + perimeter + " and your perimeter after the calculation is " + calculation + ".");
this.perimeter=calculation;
return calculation;
}
#Override
public double getPerimeter() {
// TODO Auto-generated method stub
return perimeter;
}
}
public class MainMethod {
public static void main(String[] args) {
Calculatable perimeter1 = new rectangle(20.5 , 50);
perimeter1.calculate(5);
Calculatable perimeter2 = new square(10.5);
perimeter2.calculate(2);
Calculatable[] perimetersums = new Calculatable[5];
perimetersums[0] = perimeter1; //new rectangle(20.5 , 50);
perimetersums[1] = perimeter2;// new rectangle(10 , 25);
System.out.println("the sum is= "+sumCalculate(perimetersums));
}
private static double sumCalculate ( Calculatable[] perimetersums)
{
double sum=0.0;
for(int i=0;i<perimetersums.length;i++)
{
Calculatable cal=perimetersums[i];
if(cal!=null)
sum=sum+cal.getPerimeter();
}
return sum;
}
}
I changed the class structure a little bit...
public interface Calculatable {
public double calculate();
}
public class square implements Calculatable {
private final int x=2;
public double side;
square(double side){
this.side = side;
}
public double getside(){
return side;
}
public double calculate() {
double perimeter = side * 4;
System.out.println("This calculate method will output the perimeter divided by the parameter x");
double calculation = perimeter / x;
System.out.println("The original perimeter was " + perimeter + ". And the calculated perimeter is " + calculation +".");
return calculation;
}
}
public class rectangle implements Calculatable {
private final int x=5;
public double length;
public double width;
rectangle(double length , double width){
this.length = length;
this.width = width;
}
public double getlength(){
return length;
}
public double getwidth(){
return width;
}
public double calculate() {
double perimeter = 2 * (length + width);
double calculation = 2 * perimeter;
System.out.println("This will return the perimeter of the rectangle times the x paramater");
System.out.println("Your current perimeter is " + perimeter + " and your perimeter after the calculation is " + calculation + ".");
return calculation;
}
}
public class MainMethod {
public static void main(String[] args) {
Calculatable perimeter1 = new rectangle(20.5 , 50);
// perimeter1.calculate(5);
Calculatable perimeter2 = new square(10.5);
//perimeter2.calculate(2);
Calculatable[] perimetersums = new Calculatable[5];
perimetersums[0] = new rectangle(20.5 , 50);
perimetersums[1] = new rectangle(10 , 25);
System.out.println("the sum is= "+sumCalculate(perimetersums));
}
private static double sumCalculate ( Calculatable[] perimetersums)
{
double sum=0.0;
for(int i=0;i<perimetersums.length;i++)
{
Calculatable cal=perimetersums[i];
if(cal!=null)
{
sum=sum+cal.calculate();
}
}
return sum;
}
}

Java - Error initialising Object Array List

I am getting a null pointer exception when I try to use the perimeter function in my code. It seems that the Points array (Point is a simple object with an x and y coordinate) is not correctly initialising, I believe I may have declared the array wrongly or the constructor is incorrect.
package shapes;
import static java.lang.Math.*;
public class Triangle {
private int sides = 3;
private Point[] Points = new Point[sides];
public Triangle(Point[] vertices) {
vertices = Points;
}
public double perimeter() {
return Points[0].distance(Points[1]) + Points[1].distance(Points[2]) + Points[2].distance(Points[0]);
}
public double area() {
double semiperimeter = perimeter() / 2;
return sqrt(semiperimeter * (semiperimeter - Points[0].distance(Points[1])) * (semiperimeter - Points[1].distance(Points[2])) * (semiperimeter - Points[2].distance(Points[0])));
}
#Override
public String toString() {
return "Triangle has perimeter of " + perimeter() + " and an area of " + area();
}
public void translate(int dx, int dy) {
for(int i = 0; i < 3; i++) {
Points[i].translate(dx, dy);
}
}
public void scale(int factor) {
for(int i = 0; i < 3; i++) {
Points[i].scale(factor);
}
}
public Point getVertex(int i) {
return Points[i];
}
}
Any help is much appreciated!
You need to reverse this in your constructor:
vertices = Points;
to
Points = vertices ;
You need to initialize your Points array with the input vertices and not the other way around.

Categories