Member Avatar for Gsterminator

How do i call back a variable in void method into the main method??

public void multiply (int x)
	{
		Vector3 v3 = new Vector3(num1*x,num2*x,num3*x);
	}

Recommended Answers

All 6 Replies

What do you mean by "call back"? The simplest and the logical way would be to change the return type of your method to "Vector". Some other approaches would be to pass in a reference to Vector and update the Vector in your "multiply" method or have a static member in your main class but then again not recommended.

Member Avatar for Gsterminator

i'm trying to change the components in variable v3.I already have different components in the main but i want to change v3 from my "class Vector3"/void multiply method this is what i have:

public static void main ( String [] args ) throws Exception
   {
      Vector3 v1 = new Vector3(1,2,3);
      System.out.println("v1 = " + v1);
      Vector3 v2 = new Vector3(2,7,1);
      System.out.println("v2 = " + v2);
      Vector3 v3 = v1.add(v2);
      System.out.println("v3 = " + v3);
      v3.multiply(5);
      System.out.println("v3 = " + v3);

Create the Vector as Instance or Class Variable.

Member Avatar for Gsterminator

i did create a class variable: class Vector3....and here's the code:

class Vector3
{
	public Vector3 v3;
	private int num1;
	private int num2;
	private int num3;
//------------------------------------------------------------------------
	public Vector3( int num1, int num2, int num3)
	{
		this.num1 = num1;
		this.num2 = num2;
		this.num3 = num3;
	}
//------------------------------------------------------------------------
	public String toString()
	{
		return "(" + num1 + "," + num2 + "," + num3 + ")";
	}
//------------------------------------------------------------------------
	public Vector3 add(Vector3 t)
	{
		return new Vector3(num1 + t.num1 , num2 + t.num2 , num3 + t.num3);
	}
//------------------------------------------------------------------------
	public void multiply (int x)
	{
		Vector3 v3 = new Vector3(num1*x,num2*x,num3*x);
		return; //my problem is here
	}

If you plan on making your Vector3 class immutable, you have no option but to "return" Vector3 from your "multiply" method.

Without the restriction of immutable classes, it would be as simple as modifying the state variables of that given instance; you don't even need "v3".

public void multiple(int x) {
  this.num1 *= x;
  this.num2 *= x;
  this.num1 *= x;
}
Member Avatar for Gsterminator

wow! thanks soo much and it makes complete sense

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.