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.
Related
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];
}
}
If there is an array such as:
//....
int[] anArray;
anArray = new int[3];
anArray[0] = new otherClassWConst( x, y , z);
anArray[1] = new otherClassWConst( x, y , z);
anArray[2] = new otherClassWConst( x, y , z);
//....
With the values of x and y and z all being of different value to the other x, y, and z's from the other objects in the array. (Does that make sense? Like the value of x in anArray[0] is not the same as the value found in anArray[2]). Note: there is a constructor from another class that requires those parameters, I'm not sure if thats important
How do I, in a different class, get the value of one of the parameters (for example, the value of y) in each of the array values. As in, is there a way I can get all three values of the Ys so I can add them all up together in another class?
For example
//code attaining only the y values of the array
overallValueOfY = Y + Y + Y; // or something of that nature
//life continues over here.
Please tell me if something is unclear, I tried so hard to explain. Thank you for the consideration.
OtherClassConst will need to supply a get method for it:
public class OtherClassConst {
private int x;
private int y;
private int x;
public (int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
public int getY() {
return y;
}
/* Same concept for getX() and getZ() */
}
Then, you class can call it:
int sumY = 0;
for (OtherClassConst c : myArray) {
sumY += c.getY();
}
First off, your array won't work unless your new class extends Int, I just want to make sure you know that.
Now, all you have to do is in that new class create an int varriable
int x;
int y;
int z;
and set them equal to what is put in the constructor. Then create a new method that returns the values
public int getX(){
return this.x;
}
public int getY(){
return this.Y;
}
public int getZ(){
return this.Z;
}
You need to create POJO for your other class with x,y and z instance variables, then using setter method of y you can get the values. Iterate over them to get the sum of values.
If you other OtherClass has a getY method that returns an integer then you can use the following to sum them:
Arrays.stream(anArray).mapToInt(OtherClass::getY).sum();
It is worth getting use to using streams rather than for loops.
I have been having an issue when adding objects to an array. It seems that every single time I add a new WoodFloor object to the array, it overwrites all of the other values of the array. Here's my code:
package code;
public class Main {
private static Block[] blocks = new Block[12];
public static void main(String[] args) {
for(int i = 0; i < 12; i++) {
blocks[i] = new WoodFloor(i * 10, i * 20);
}
}
}
package code;
public class Block {
protected static int x, y;
public Block(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
package code;
public final class WoodFloor extends Block {
public WoodFloor(int x, int y) {
super(x, y);
}
}
Don't use static modifier for class fields that need to be different for each instance. The static modifier makes the field a class field, one that is effectively shared by all instances, and this is not what you want.
So change this:
protected static int x, y;
to this:
protected int x, y;
Your program produces 12 different objects, but they all reference the same pair of x and y. The problem is on this line:
protected static int x, y;
// ^^^^^^
When you make a field static, you are saying that the value of this field is going to be the same in every single object of the class. This is definitely not what you are trying to achieve here: you need each WoodFloor to have its own x and y. For that, you use instance fields (i.e. fields declared without static).
Static makes the variable available at the class lever so an instance is not needed to access it. Here effectively resets it to its original value each time rather than moving to the next array position and forgets the old array.
I'm suspecting it's the 'static' keyword for x and y.
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;" .
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I am trying to access a private variable (x) in my method distanceFromPoint but it seems it doesn't work. How can I access it? My method is returning 0.0 all the time regardless of other values.
Code
public class Pointdeclare {
private static int x;
private static int y;
Pointdeclare (int x_ , int y_ ){
this.x = x_;
this.y = y_;
}
int getX(){
return x;
}
int getY(){
return y;
}
static double distanceFromZero (){
return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
}
double distanceFromPoint(Pointdeclare point){
int distX = point.getX()- this.x;
int distY = point.getY()- this.y;
return (double) Math.sqrt(Math.pow(distX, 2) + Math.pow(distY, 2));
}
}
Main Class
public class main {
static Pointdeclare p1 = new Pointdeclare(6, 7);
static Pointdeclare p2 = new Pointdeclare(3, 7);
public static void main (String[] args){
System.out.println(p2.distanceFromZero());
System.out.print(p1.distanceFromPoint(p2));
}
}
This will work better for you:
package cruft;
/**
* Point2 description here
* #author Michael
* #link http://stackoverflow.com/questions/14087002/how-to-access-private-variables-in-a-java-class-method
* #since 12/29/12 6:52 PM
*/
public class Point2 {
private int x;
private int y;
Point2(int x_, int y_) {
this.x = x_;
this.y = y_;
}
int getX() {
return x;
}
int getY() {
return y;
}
double distanceFromZero() {
return distanceFromPoint(new Point2(0, 0));
}
double distanceFromPoint(Point2 point) {
int distX = point.getX()-this.x;
int distY = point.getY()-this.y;
return (double) Math.sqrt(Math.pow(distX, 2)+Math.pow(distY, 2));
}
public static void main(String[] args) {
Point2 p1 = new Point2(6, 7);
Point2 p2 = new Point2(3, 7);
System.out.println(p2.distanceFromZero());
System.out.print(p1.distanceFromPoint(p2));
}
}
You shouldn't declare your class fields as static, just leave them private.
Btw consider using Point or Point2D native classes from java.awt.geom package.
You declared "x" and "y" static, which means that they're class variables, not instance variables.
Because of that, every new call to the constructor will overwrite the old values. Thus distanceFromPoint always returns zero because there's only one x and one y.
The problem is not due to private, instead, it's because of static. x is static. In your method, you should use x as:
int distX = point.getX()- Pointdeclare.x; // You could use this.x because x is static.
I hope you find this relevant, it doesn't answer your question directly but I was recently informed my understanding of static was incorrect so having just researched the topic I thought maybe I could help. Static variables belong to a class and not its objects, objects of a class may access a static variable but no matter how many objects of the class there are there will only be one copy of the static variable. So I think what the people before me were saying is instead of p1 and p2 having their own copies of x and y both objects share the same x and y field therefore your value returned is 0. In other worlds your trying to find the distance between one location, it will always be zero. Hopefully that helps :-). I'm sorry I missed the first line of the main method. p2 should return a value as long as it isn't zero but p1 will not.