0

Hi everyone i am trying to write in Java the 2 methods "manipulators" or "setters" which will fill the 2 attributes of this class their names will be as follows: vSetX for the abscissa and vSetY for the ordinate. i have to create a method "accessors" or "getters" allowing to display the coordinate of a point in different formats like: • (2.5; -3.0) • x = 2.5 and y = -3.0 • Abscissa of 2.5 - Y-coordinate of -3.0 • ... My method will have the following name sGetCoordonneeCartesienne. It will receive a parameter of type character which allows to know the display to achieve. My problem right now is when i compile it gives me a NullPointer but i think i have satisfied the conditions to print out the coordinates

import java.util.Scanner;

public class CoordoneeCartisienne {
// les attributes
private int[] coordinates;

// Constructeur defaut
public CoordoneeCartisienne() {
    coordinates[0] = 0;
    coordinates[1] = 0;

}  

// mon constructor
public CoordoneeCartisienne(int abscisse, int ordonnee) {
    coordinates[0] = abscisse;
    coordinates[1] = ordonnee;
}

public void vSetX(int  abscisse) {
    coordinates[0] =  abscisse;
}

public void vSetY(int ordonnee) {
    coordinates[1] = ordonnee;
}

public String sGetCoordonneeCartesienne(char display) {

    switch (display) {
    case 'A':
        return "(" + coordinates[0] + "; " + coordinates[1];
    case 'B':
        return "x = " + coordinates[0] + " et y = " + coordinates[1];


    }

    return "null";
}

that was my class and constructors and here is the main import java.util.Scanner;

public class Labo6Etape3 {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner sc = new Scanner(System.in);
    System.out.println("Saisir votre coordonee (abscisse et ordonee)");

    char x =  sc.next().charAt(0);
    char y =  sc.next().charAt(0);

    CoordoneeCartisienne myObject = new CoordoneeCartisienne(x , y);
    String input = sc.nextLine();
    myObject.sGetCoordonneeCartesienne(x);
    myObject.sGetCoordonneeCartesienne(y);

}

} The code is a little long but its because my teacher is making me create everything using a class and constructor and i have a problem understanding it. Thanks in advance for those who could help me

Quang Cao
  • 15
  • 6
  • Does this answer your question? [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Arvind Kumar Avinash May 10 '20 at 20:57
  • I understand what is a nullpointer but the problem is i dont really see how that apply’s to me conscidering i have to return a string using a char – Quang Cao May 10 '20 at 20:58

1 Answers1

0

There is no initialization for private int[] coordinates; so it stays null and you get NullPointerException in constructor trying to access its first element.

You should initialize array. For example:

private int[] coordinates = new int[2];
Serikov
  • 934
  • 7
  • 12