Java wrong output class variable [duplicate] - java

This question already has answers here:
What is object field initialization and constructor order in Java
(3 answers)
Are fields initialized before constructor code is run in Java?
(5 answers)
Primitives/Objects Declaration, default initialization values
(1 answer)
Closed 4 months ago.
why is the output 0.0 if I write the following code? It seems to me like it wouldn't read the variable x inside my class Car.
public class Car {
double x = 2;
double y;
double v = x * y;
public Car(double y) {
this.y = y;
}
public static void main(String[] args) {
Car car = new Car(100);
System.out.println(car.v);
}
}//end of class

The v is being calculated before the y is set in the constructor, so it will always equal 2*0, so 0.
You can do the v calculation inside the constructor instead.
public class Car {
double x = 2;
double y;
double v;
public Car(double y) {
this.y = y;
v = x * y;
}
}

your double v = x * y line is being done on instantiation of a car object, when x is 2 and y is unititialized (0). You need to move that line into the constructor if you want it to update with the proper value.

I have included some System.out inside the constructor to get the flow of the execution.
Here, the value of v is already assigned with value of x and y where x = 2 and y = 0.0.
So,you can modify your code as below:
Code:
Car.java
public class Car {
double x = 2;
double y;
double v;
public Car(double y) {
System.out.println("Inside constructor");
System.out.println("value of v here:" + v);
this.y = y;
v = x * y;
System.out.println("value of v now:" + v);
}
}
Test.java
public class Test {
public static void main(String[] args) {
Car car = new Car(100);
System.out.println(car.v);
}
}
Output:
Inside constructor
value of v here:0.0
value of v now:200.0
200.0

Related

Constructor undefined while using multiple classes

I have a question. For the first time, I am working with multiple classes in JAVA. I have some trouble doing this. I created a class which I will call from another class. I want to make a type Coordinate, which, as the name suggests, holds coordinates. then, I want to shift those coordinates. So far the code looks as follows:
public class Coordinate {
double x;
double y;
Coordinate(){
x=0;
y=0;
}
public Coordinate(int x, int y){
this.x = x;
this.y = y;
System.out.print(x);//TO TEST WHETHER IT DOES SOMETHING
}
Coordinate shiftCoordinate(int z, int w){
this.x = x + z;
this.y = y+ w;
return new Coordinate(x,y);//ERROR: The constructor Coordinate(double, double) is undefined
}
}
It throws an error where stated. I do not understand this error. In my 'main' class, I did the following:
void start() {
Coordinate coordinate = new Coordinate();
coordinate.x=3;
coordinate.y=4;
}
I would expect this to print 3, but it does not. Where am I wrong?
First you don't work with mutiples class, only one : Coordinate but you want multiple constructors.
As your attributs are double make a constructor that needs that type, it'll be used when you write new Coordinate(5,6)
public Coordinate(double x, double y) {
this.x = x;
this.y = y;
}
If you want a default constructor (no args) it'll be used when you call new Coordinate()
You want a way to shift from a Coordinate instance you have 2 ways : modify the current instance or create a new one, but don't do both together (like your code) it's not usefull to get at the end 2 objects whith the same values
// modify current instance
void shiftCoordinate(double z, double w) {
this.x = x + z;
this.y = y + w;
}
// return a new object
Coordinate shiftCoordinate(double z, double w) {
return new Coordinate(this.x + z, this.y + w);
}
Also you last code uses the default constructor with no args so that's normal you don't see any printing use new Coordinate(3,4) to see it
A classic constructor is also, the constructor to clone an instance, it takes an instance and create a new one with the same values :
public Coordinate(Coordinate clone) {
this.x = clone.x;
this.y = clone.y;
}
public Coordinate(int x, int y){
this.x = x;
this.y = y;
System.out.print(x);
}
This constructor has arguments that are integers, and you're trying to pass in doubles. Change the constructor to this:
public Coordinate(double x, double y){
this.x = x;
this.y = y;
System.out.print(x);
}

How to get Anonym Objects parameters?

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.)

Initialization of Class fields

public class InitializationTest {
private int x;
private int y;
private int sumOFXandY = x + y;
public InitializationTest(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getSumOFXandY() {
return sumOFXandY;
}
}
class Tester {
public static void main(String[] args) {
InitializationTest initializationTest = new InitializationTest(5, 6);
System.out.println(initializationTest.getX());
System.out.println(initializationTest.getY());
System.out.println(initializationTest.getSumOFXandY());
System.out.println(initializationTest.getX() + initializationTest.getY());
}
}
Output:
5
6
0 //Why not 11?
11
In the example above my brain cannot understand such simple thing - a revelation.
When the class is created, its fields are initialized with default values. In this case those are 0.
Upon calling the constructor x is initialized with 5 and y is initialized with 6. Why then sumOFXandY is somewhere aside and still is initialized with 0 even after calling the constructor. Why is not it initialized with 5 + 6 = 11 ?
Because it(sumOFXandY) cannot be re-initialized after the constructor gets executed. When you create an object, it initializes the instance variables that are initialized inline (here it is sumOFXandY = x + y). Then the constructor block gets executed.
To solve this, move sumOFXandY = x + y inside the constructor.

Constructor is not defined in java in eclipse though it is defined [duplicate]

This question already has answers here:
What causes error "No enclosing instance of type Foo is accessible" and how do I fix it?
(11 answers)
Closed 7 years ago.
Help Please....
I am new in Java. I am trying to write a code that contains a class "point" into a public class "PeterAndSnowBlower" in Eclipse(Luna).
I have also tried by making the variables x, y public in the class "point" and it gives the same error.
I have also used this.x and this.y instead of x and y inside the constructors
Here is my code:
import java.util.*;
public class PeterAndSnowBlower {
class point{
int x;
int y;
public point() {
x = y = 0;
}
public point(int a, int b){
x = a;
y = b;
}
public point(point p) {
x = p.x;
y = p.y;
}
public double distance(point P){
int dx = x - P.x;
int dy = y - P.y;
return Math.sqrt(dx*dx + dy*dy);
}
}
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int n, x, y;
point P = new point(0, 0);
n = in.nextInt();
P.x = in.nextInt();
P.y = in.nextInt();
Vector<point>points = new Vector<point>();
for(int i = 0; i < n; i++){
x = in.nextInt();
y = in.nextInt();
points.add(new point(x, y));
}
double r1, r2;
r1 = r2 = P.distance(points.get(0));
for(point point:points){
r1 = Math.max(r1, P.distance(point));
}
}
}
the error is:
Multiple markers at this line
- No enclosing instance of type PeterAndSnowBlower is accessible. Must qualify the allocation with an enclosing instance of type PeterAndSnowBlower (e.g.
x.new A() where x is an instance of PeterAndSnowBlower).
- The constructor PeterAndSnowBlower.point(int, int) is undefined
Unless the inner class is defined static, you cannot instantiate it from static method from outer class. The non-static class requires this reference to outer class.
Here it makes sense to declare this class as static. Obviously it doesn't refer to outer class.
You're statically accessing your inner class (meaning you don't do it from an instance of the outer class).
What you need is a static inner class, which makes perfect sense here as the inner class doesn't refer to the outer one.
Change the declaration to
static class point {

Static Vector Multiply - No New Objects

Is there a way to have a static method such that it returns a Vector object (with a simple integer x and y value as fields) which is a Vector multiplied by an int value argument. However, there are no new objects made, i.e, the object assigned to the return value is changed instead of there being a new Vector created?
The following code does not achieve this:
public class Vector{
public int x,y;
public Vector(int x,int y){
this.x = x;
this.y = y;
}
//Important code starts
public static Vector mult(Vector v,int a){
return new Vector(v.x*a,v.y*a);
}
//Important code stops
}
This code is what I'm after but it's too messy:
public static Vector mult(Vector v1,Vector v2,int a){
v1.x = v2.x*a;
v1.y = v2.y*a;
}
Is there an alternative?
Why not add:
public void multiply(Vector otherVector, int a){
x = otherVector.x * a;
y = otherVector.y * a;
}
to your Vector class.
Do you mean?
public void mult(double a) {
x *= a;
y *= a;
}

Categories