java - Creating objects from constructors -


i newbie java, been fiddling code while.

public class threevector { private double x,y,z;   // definign local variables   public threevector(){} // constructor has no input  public threevector (double va1,double va2, double va3){va1=x;va2=y;va3=z;};// creatign constructor , can used calling method later // takes 3 values   public double magnitude (){     double y1= math.sqrt(x*x+y*y+z*z);     return y1 ; // finds magnitude of vector }  public threevector unitv(){      threevector unitv= new threevector (); unitv.threevector(x/magnitude(),y/magnitude(),z/magnitude()); } 

now here stuck. created object unitv call threevector constructor, compiler keeps saying create new method threevector. not sure whats going on...

a constructor can called only using new keyword. you're doing here:

unitv.threevector(x/magnitude(),y/magnitude(),z/magnitude()); 

is calling method called threevector, compiler complains there's no such method in threevector class.

to fix this, must use threevector constructor arguments create unitv instance instead:

public threevector unitv(){     threevector unitv = new threevector(x/magnitude(),y/magnitude(),z/magnitude());     //and, of course, return threevector instance     return unitv; } 

and code can shorten to

public threevector unitv() {     return new threevector(x/magnitude(),y/magnitude(),z/magnitude()); } 

but since can have x, y , z 0 value @ same time, better change logic in unitv method first magnitude value , doing evaluation, in order avoid division 0:

public threevector unitv() {     double magnitude = magnitude();     if (magnitude != 0) {         return new threevector(x/magnitude, y/magnitude, z/magnitude);     }     return new threevector(0, 0, 0); } 

by way, constructor logic wrong, you're assigning fields values arguments, should other way around:

public threevector (double va1,double va2, double va3) {     x = va1;     y = va2;     z = va3 } 

Comments

Popular posts from this blog

c++ - Creating new partition disk winapi -

Android Prevent Bluetooth Pairing Dialog -

VBA function to include CDATA -