-5

What is the possible way to scan a point in java ? Should I read point.x then point.y or can I read the two co-ordinates at once ?

import java.awt.Point;
import java.util.Scanner;
public class Saleelo {
    public static void main(String[] args) {
        int n = 5;
        Scanner scan = new Scanner(System.in);
        Point[] Points = new Point[60];
        for (int i=0 ; i < n ; i++) {
            Points[i].x = scan.nextInt();
            Points[i].y = scan.nextInt();
            System.out.println(Points[i]);
        }   
    }
}

This what I have tried and it gives me null pointer exception

  • 1
    How do you want the user to enter points? That really answers your first question by definition. The reason you get an NPE is that new never _create_ the `Point` - `Points[i] = new Point()`; and array is initialised to `null`. Also, stick to Java naming conventions, variables should be in `camelCase`. – Boris the Spider Apr 16 '15 at 16:17
  • Not surprising. you didn't initialize anything in `Points` so `Points[i].x` is probably throwing your null pointer. – tnw Apr 16 '15 at 16:18

1 Answers1

1

Instantiate each array element before attempting to assign values to its elements

for (int i=0 ; i < points.length ; i++) {
    points[i] = new Point();
    ...

where the points array is initialized with just the 5 elements that you will use

Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • I would add to this answer that there is no point in creating a `Point[60]` if the length if already fixed to 5. Upvoted. – Jean-François Savard Apr 16 '15 at 16:20
  • @Jean-François Savard: there is no point in creating the array at all… – Holger Apr 16 '15 at 16:32
  • @Holger Certainly for a `println` only, but I believe this is a simplified snippet. – Jean-François Savard Apr 16 '15 at 16:33
  • 1
    @Jean-François Savard: under the premise that this is a simplified example, there might be a use for the other 55 array entries as well. To add something to the answer, I’d recommend to initialize the value at construction, i.e. `points[i] = new Point(scan.nextInt(), scan.nextInt());` instead of using three statements like `points[i] = new Point(); points[i].x = scan.nextInt(); points[i].y = scan.nextInt();` – Holger Apr 16 '15 at 16:36
  • @Holger I agree that your addition is better. As for the 55 other entries, I don't really see how they could be used logically if we have an `n` variables which represent the length of input. – Jean-François Savard Apr 16 '15 at 16:46