-5

I'm a student , our teacher told us to make a static method called SOMME to count the vectors sum , ( it's called SOMME in the code ) and he said it should be static , I didn't know where the problem is I tried almost every possible way to solve that but no solutions.

here is the Code :

import java.util.*;
public class Vecteur {// 3D

    public double x;
    public double y;
    public double z;

    public Vecteur (double x,double y,double z ) 
    {

        this.x=x;
        this.y=y;
        this.z=z;
    }


    public void affichage ()
    {  
        System.out.println("("+x+","+y+","+z);
    }

    public double norme() 
    {   
        return Math.sqrt(x*x+y*y+z*z);
    }

    public static Vecteur somme(Vecteur v) // he told us to make it static nom matter what 
    {
         Vecteur u=new Vecteur(0.0,0.0,0.0);

         u.x=x+v.x;
         u.y=y+v.y;
         u.z=z+v.z;

         return u;
    }

    public double produit(Vecteur v)
    {
        return x*v.x+y*v.y+z*v.z; 
    }
}
Frakcool
  • 10,915
  • 9
  • 50
  • 89
aminou757
  • 3
  • 1

2 Answers2

1

If you want it static you will have to do it like this:

public static Vecteur somme(Vecteur v1, Vecteur v2) 
{
     Vecteur u = new Vecteur(v1.x + v2.x, v1.y + v2.y, v1.z + v2.z);
     return u;
}

The only way to do it with just one parameter and being able to use your own values is with a non-static method like this:

public Vecteur somme(Vecteur other)
{
    Vecteur u = new Vecteur(this.x + other.x, this.y + other.y, this.z + other.z);
    return u;
}

I recommend you to check this out though. I added both to your class below:

public static class Vecteur {// 3D

public double x;
public double y;
public double z;

public Vecteur (double x,double y,double z ) 
{

    this.x=x;
    this.y=y;
    this.z=z;
}


public void affichage ()
{  
    System.out.println("("+x+","+y+","+z);
}

public double norme() 
{   
    return Math.sqrt(x*x+y*y+z*z);
}

public static Vecteur somme(Vecteur v1, Vecteur v2) // he told us to make it static nom matter what 
{
     Vecteur u = new Vecteur(v1.x + v2.x, v1.y + v2.y, v1.z + v2.z);
     return u;
}

public Vecteur somme(Vecteur other)
{
    Vecteur u = new Vecteur(this.x + other.x, this.y + other.y, this.z + other.z);
    return u;
}

public double produit(Vecteur v)
{
    return x*v.x+y*v.y+z*v.z; 
}

}

Raudel Ravelo
  • 648
  • 2
  • 6
  • 24
0

Why the code does not work

You are trying to access an instance variable from a static method, which will not work.

How you can fix this

There 2 ways to do this:

  • Take both vertors as parameters to the method, and get all the values from the parameters
  • Make the method non-static to allow it to access instance methods
jrtapsell
  • 6,719
  • 1
  • 26
  • 49