pass array to a class as an argument - java

I am trying to pass an array to another class as an argument but keep getting the error
"error: incompatible types: Point cannot be converted to int[]"
the first portion of my code is:
public Circle(int n, int x, int y)
{
radius = n;
counter++;
center[0] = x;
center[1] = y;
Point center = new Point(center);
}
Point is the class that needs to have the array passed to it.
the second portion of code:
public class Point
{
private int xCord;
private int yCord;
public Point (int [] center)
{
xCord = center[0];
yCord = center[1];

This is unclear to me, however it should clearly cause an error in the circle class constructor.
center[0] = x; // center is an int array
center[1] = y;
Point center = new Point(center); // ?????
// ^^^ ^^^^ Duplicate variable names
Fix this by changing the name of the new Point variable.

Point center = new Point(center);
Duplicate variable
Change to
Point point = new Point(center);

You have to consider Object here. The variable name here is duplicate. As the center objects hold the array reference you cannot keep the same variable to hold the point object.
You can modify your code accordingly. Attached you sample code
public class Test {
public static void main(String[] args) {
Circle(1,2,3);
}
static void Circle(int n, int x, int y)
{ int center[] = new int[2];
//Do your operation and initialize the array
center[0] = 25;
center[1] = 26;
Point pointObject = new Point(center);
}
}
class Point
{
private int xCord;
private int yCord;
public Point (int [] center)
{
xCord = center[0];
yCord = center[1];
}
}

Related

Call method on multidimensional array

Let's say I have a method like so:
public class ColoredPoint {
private final Color color;
private final int x;
private final int y;
public ColoredPoint(int x, int y, Color color) {
this.x = x;
this.y = y;
this.color = color;
}
public ColoredPoint(int x, int y, int color) {
this(x,y, new Color(color));
}
public int getX() {
return x;
}
}
Then I populate a single dimension array with some data like so for example:
public class DemoInput {
final static ColoredPoint[] test2 = new ColoredPoint[]
{ new ColoredPoint( 208, 324, -1 )
, new ColoredPoint( 154, 313, -1 )
, new ColoredPoint( 288, 316, -1 )
, new ColoredPoint( 312, 296, -1 )
}
How can I figure out the biggest x in the array? I have a method to get x from the ColoredPoint so this should be easy, right?
I know I can use a for-loop for this. I just don't now to to get the x from the ColoredPoint inside the array.
I want the x value of a ColoredPoint in the array called test2 in the class DemoInput so I thought:
DemoInput.test2.ColoredPoint.getX[i]
would do the trick but that doesn't work.
Can anyone help me out? Also, how would it work for a multidimensional array, like such:
allTests = new ColoredPoint[][]
{ test1
, test2
};
You need to first get a ColoredPoint element from the array (using the [] operator), and then call the getX() method on it:
x = DemoInput.test2[i].getX()
// Here -----------^
The same logic applies for a 2D array - using the [] operator will return a 1D array, on which you'll need to use the [] operator in order to get a ColoredPoint element:
x = DemoInput.allTests[i][j].getX()
// Here --------------^
Java streams are pretty useful for finding things like largest and smallest:
Arrays.stream(test2).mapToInt(ColoredPoint::getX).max();
Multi-dimensional is slightly less elegant:
Arrays.stream(allTests).map(Arrays::stream)
.flatMapToInt(test -> test.mapToInt(ColoredPoint::getX)).max();
This is a possible implementation
public class ColoredPoint implements Comparable<ColoredPoint> {
private final Color color;
private final int x;
private final int y;
public ColoredPoint(int x, int y, Color color) {
this.x = x;
this.y = y;
this.color = color;
}
public ColoredPoint(int x, int y, int color) {
this(x, y, new Color(color));
}
public int getX() {
return x;
}
#Override
public int compareTo(ColoredPoint o) {
return Integer.compare(this.x, o.x);
}
public static void main(String[] args) {
ColoredPoint[] test2 = new ColoredPoint[]{new ColoredPoint(208, 324, -1)
, new ColoredPoint(154, 313, -1)
, new ColoredPoint(288, 316, -1)
, new ColoredPoint(312, 296, -1)
};
Optional<ColoredPoint> maxColor = Arrays.stream(test2).max(ColoredPoint::compareTo);
maxColor.ifPresent(coloredPoint -> System.out.println("Max X = " + coloredPoint.getX()));
}
}
This is a Java 8 compatible solution.
Hope this helps!

New Instances of Objects Set to Identical Values

public class TriVal {
private static int x;
private static int y;
private static int z;
TriVal(int x, int y, int z) {
TriVal.x = x;
TriVal.y = y;
TriVal.z = z;
}
public int sum(TriVal p2) {
int a = Math.abs(TriVal.x + p2.x);
int b = Math.abs(TriVal.y + p2.y);
int c = Math.abs(TriVal.z + p3.z);
int sum = a + b + c;
return sum;
}
}
This is a piece of a constructor for an object that contains a set of 3 values.
However, I am writing a function that creates a new TriVal made by summing the x, y, and z, of two instances of this object.
So say we have
TriVal p1 = new TriVal(10, 10, 10);
TriVal p2 = new TriVal(20, 20, 20);
calling the function
p1.sum(p2)
(Which is included elsewhere in the class) should return 90.
However, it returns 120.
I am learning that upon creating a new instance of the TriVal Object, the previously defined p1 instance is somehow being set to the same values as p2, which explains the sum being 120.
I believe this error is located somewhere in my constructor, perhaps in the way I am updating values or declaring variables at the top of the class?
Any helpful tips would be appreciated, thank you!
private static int x;
private static int y;
private static int z;
You declared your instance member as static which will be same for all the instances. They store last assigned values. remove static and you'll be fine.
As #Orin pointed, you'll need to change the code a bit where you should bind your parameters to instance members.

declare 2d variable Java

I am wondering whether it is possible to assign a value to a variable that would point to some exact position in the 2d Array in Java.
I am accessing array element through
imageMatrix[width][hight].getColor1()
and since I am considering different scenarios, it would be easier to declare [width][high] by eg. n1=[2][1] and then call
imageMatrix(n1).getColor1()
Is it somehow possible? Thanks!
You can define a class Coordinate that contains the width and height of a cell of your 2d array. Then use an instance of this class to your imageMatrix() method.
Something like:
public clas Coordinate{
private int height;
private int width;
/*Accessors and constructors...*/
}
You can define ImageMatrix and Point as class.
For setting and getting color of each point you can create method inside Point class.
Here we are storing each point in a list so that we can access them in future.
import java.util.ArrayList;
public class ImageMatrix {
Point point;
public ImageMatrix(Point point){
this.point = point;
}
public static void main(String[] args) {
//to set color and store each point into a list
ArrayList<Point> pointList = new ArrayList<>();
//creating 9 points with different color
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
Point point = new Point(i,j);
point.setColor("color"+i+j);
pointList.add(point);
}
}
//to get color from each point
for(Point point : pointList){
System.out.println("color of point " + point.height +" and " + point.width +" is : " + point.getColor());
}
}
}
class Point{
public int height;
public int width;
public String color;
public Point(int height, int width){
this.height = height;
this.width = width;
}
public void setColor(String color){
this.color = color;
}
public String getColor(){
return this.color;
}
}

Array of random numbers as Object in java

I am new at java and want to ask you one question. So first what I have to do: My goal is to create different points in one area. I decided to create a class Koord for saving the coordinates of the points. I have used an array of 2 elements for this - for the x and y value. After that I added a random generator for x and y (they have to be random).
Here is my class:
import java.util.Random;
public class Koord {
private int number;
private static int numberOfNodes = 0;
public static int[] koord;
public Koord(int x, int y){
koord = new int[2];
koord[0] = x;
koord[1] = y;
number = ++numberOfNodes;
}
public int getNumber() {
return number;
}
public static int getNumberOfNodes() {
return numberOfNodes;
}
private static int randomFill(){
Random rand = new Random();
int randomNum = rand.nextInt(99);
return randomNum;
}
public int getX(){
return koord[0] = randomFill();
}
public int getY(){
return koord[1] = randomFill();
}
}
So, until now everything is OK. But now at my main class, I want to create some points and add them to a list. This is also not a problem. The problem starts when I want to print the coordinates of the points. As I am calling the methods getX() when I am printing the coordinates of the points in the list, I am getting different coordinates every time.
import java.util.LinkedList;
import java.util.ListIterator;
public class Display {
public static void main(String args[]) {
LinkedList<Koord> ownArea = new LinkedList<Koord>();
Koord point1 = new Koord(0, 0);
Koord point2 = new Koord(0, 0);
Koord point3 = new Koord(0, 0);
Koord point4 = new Koord(0, 0);
Koord point5 = new Koord(0, 0);
Koord point6 = new Koord(0, 0);
Koord point7 = new Koord(0, 0);
ownArea.add(point1);
ownArea.add(point2);
ownArea.add(point3);
ownArea.add(point4);
ownArea.add(point5);
ownArea.add(point6);
ownArea.add(point7);
System.out.println("ListIterator Approach: ");
ListIterator<Koord> listIterator = ownArea.listIterator();
while (listIterator.hasNext()) {
System.out.println(listIterator.next().getX());
}
System.out.println("ListIterator Approach: ");
ListIterator<Koord> listIterator2 = ownArea.listIterator();
while (listIterator2.hasNext()) {
System.out.println(listIterator2.next().getX());
}
}
}
So I know where the problem is, I know that this is wrong, but I don't know how to assign static coordinates to every point and how to print them. And I need this, because I want to operate with the coordinates (comparing them, printing them and so on). I know I have to learn a lot, but for now it will be very helpful, if you can give me some advice.
Since you are calling randomFill() every time you try to getX() or getY() It will be better to initialize every Koord object with the X and Y value already randomized.
Example:
Random rand = new Random();
LinkedList<Koord> ownArea = new LinkedList<Koord>();
Koord point1 = new Koord(rand.nextInt(99), rand.nextInt(99));
Koord point2 = new Koord(rand.nextInt(99), rand.nextInt(99));
ownArea.add(point1);
ownArea.add(point2);
for(Koord c : ownArea) {
System.out.println("x: " + c.getX() + " y: " + c.getY());
}
Also in your Koord class
The variable int[] koord should not be static and change
getX() and getY() to simply return the value.
In fact this would be a better approach
public class Koord {
private int number;
private static int numberOfNodes = 0;
private int x;
private int y;
public Koord(int x, int y) {
this.x = x;
this.y = y;
this.number = ++numberOfNodes;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getNumber() {
return number;
}
}
I think this is the problem
public int getX(){
return koord[0] = randomFill();
}
This makes the x random every time you call it!
Move all assignemts to the constructor, and make getX() work like an actual getter, ie. return x
I avoid posting code. You should figure it out yourself :)
You need to look at your getX() function. I have no idea why you're using randomFill() there, since it will continously return a random x value. If you want a random set of coordinates per point, but you only want them to be set once, I suggest calling randomFill() in the constructor.
public Koord() { // you don't need the x - y parameters if you're calling the random function anyways.
koord = new int[2];
koord[0] = randomFill();
koord[1] = randomFill();
number = ++numberOfNodes;
}
// you can now create points like so
Koord point1 = new Koord();
Koord point2 = new Koord();
Koord point3 = new Koord();
You'll also need to update your getX() (and getY()) :
public int getX() {
return koord[0];
}

How to use constructor in Java

Can someone please tell me what's wrong with this simple program? I'm getting output as "0".
package myConst;
public class Doconstructor
{
int length,width;
Doconstructor(int x, int y)
{
int area;
area = length * width;
System.out.println("area ="+area);
}
}
class work
{
public static void main(String args[])
{
Doconstructor d1 = new Doconstructor(10, 15);
}
}
Doconstructor d1 = new Doconstructor(10, 15);
// you are assigning values for x and y
But
Doconstructor (int x,int y)
{
int area; // you are never use x and y values for calculation
area = length *width; // so area remain 0 since current length and width is 0
System.out.println("area ="+area);
}
You need to change your code as follows.
Doconstructor (int x,int y)
{
int area;
this.length=x;
this.width=y;
area = length *width;
System.out.println("area ="+area);
}
Edit like this:-
package myConst;
public class Doconstructor
{
int length,width;
Doconstructor(int x, int y)
{
int area;
this.length=x;//Using this for current object
this.width=y;//Using this for current object
area = length * width;
System.out.println("area ="+area);
}
}
class work
{
public static void main(String args[])
{
Doconstructor d1 = new Doconstructor(10, 15);
}
}
Your output will be:
area =150
Must read this :
http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
You are not setting the values of length and width and by default they are both 0. You might have to do this:
Doconstructor(int x, int y){
int area;
area = x * y;
length = x;
width = y;
System.out.println("Area = "+area);
}
You're not using the variable values you pass to the constructor in it but rather the length and width values that have been initialized to 0. You want area = x * y; instead.
The length and width fields are implicitly initialized to 0. Multiply them and you get 0.
I think what you want is
length = y ;
width = x ;
int area = length * width ;
System.out.println("area ="+area);
You have this:
public class Doconstructor {
int length,width;
Doconstructor (int x,int y)
{
int area;
area = length *width;
System.out.println("area ="+area);
}
}
At no point do you set length or width equal to anything. Their initial values are 0 and your program is doing precisely what you told it to do. area = length * width = 0 * 0 = 0.
You also are not doing anything with the x or y that you passed to the constructor, but this probably was not your intention. When writing programs, you basically need to clearly instruct the computer to do what you want to do. It's not going to guess what you want. If you ignore x and y, and don't assign any values to length or width, then that is precisely what will happen and you cannot be surprised when you see the results you see.
you are writing int length,width at class level so length and width are set to 0 as default.
After that in the constructor you are not setting any values to length and width so you are the values for length and width are 0.Hence area is also 0
Please check this link for list of default values
Constructors are used to create objects and to set the attributes. You are not setting the attributes in your constructor. Here is how your constructor should look like.
Doconstructor(int x, int y){
length = x;
width = y;
}
Secondly you are mixing the logic of a constructor and a method. You are doing the calculation of area, which seems to be a perfect fit for another method in your class. so better move that logic in a separate method:
public int calculateArea() {
int area;
area = x * y;
return area;
}
Finally create an object using constructor to set the attributes length and width. And then call calculateArea method to do the business logic of calculating area.
public static void main(String args[]){
Doconstructor d1 = new Doconstructor(10, 15); // create object and set length & width
d1.calculateArea();
}
you are not assigning the value of x and y to the variables width and length. The default value of width and length are (int) 0. Thats why you are getting the output (0*0=0). First assign the values to the variables or use "area=x*y;" .

Categories

Resources