This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
The Program I'm trying to make is supposed to draw a Polygon using points stored in an ArrayList. I rechecked the code and I am also using the driver, but when I try to run the program, it gives me a NullPointerException when I try to add coordinates for the program to use when drawing.
import java.awt.geom.*;
import java.util.ArrayList;
import gpdraw.*;
public class IrregularPolygon
{
private ArrayList <Point2D.Double> myPolygon;
DrawingTool myPen;
SketchPad myPaper;
double dblPerimeter;
double dblSegment;
double dblArea;
public IrregularPolygon()//Creating the sketchpad and pen
{
myPaper = new SketchPad(500,500);
myPen = new DrawingTool(myPaper);
}
public void add(Point2D.Double aPoint)//Adds to the array
{
myPolygon.add(aPoint);// This is where the problem is I think, I don't know what to do
}
public void draw()//This method draws the polygon
{
for(int x = 0; x < myPolygon.size() - 1 ; x++)
{
myPen.down();
myPen.move(myPolygon.get(x).getX(),myPolygon.get(x).getY());
myPen.up();
}
}
public double perimeter()//This method finds the perimeter
{
for(int x = 0; x < myPolygon.size() - 1; x++)
{
dblPerimeter += myPolygon.get(x).distance(myPolygon.get(x+1));
}
return dblPerimeter;
}
public double area()//This method finds the area
{
for(int x = 0; x < myPolygon.size() - 1; x++)
{
double X1 = (myPolygon.get(x).getX());
double Y1 = (myPolygon.get(x).getY());
double X2 = (myPolygon.get(x + 1).getX());
double Y2 = (myPolygon.get(x + 1).getY());
dblArea += (X1 * Y2 - Y1 * X2);
}
return dblArea;
}
}
and the programs runs from this driver:
import java.util.*;
import java.awt.geom.Point2D;
public class IrregularPolygonDriver
{
static boolean blnReadyToDraw = false;
static Scanner in = new Scanner(System.in);
public static void main(String[]args)
{
int num;
IrregularPolygon poly = new IrregularPolygon();
while(blnReadyToDraw == false)
{
System.out.println("Would you like to add a point, find the perimeter, or calculate the area?");
System.out.println("To add a point, enter 1; to find the perimeter, enter 2; to find the area, enter 3");
num = in.nextInt();
if(num == 1)
{
double dblNum1;
double dblNum2;
Point2D.Double dblNumber;
System.out.println("Enter an x value and a y value: ");
dblNum1 = in.nextDouble();
dblNum2 = in.nextDouble();
dblNumber = new Point2D.Double(dblNum1,dblNum2);
poly.add(dblNumber);
System.out.println("Keep adding points until you are done drawing the figure.");
}
else if(num == 2)
{
poly.perimeter();
}
else if(num == 3)
{
poly.area();
}
else
{
blnReadyToDraw = true;
System.out.println("Preparing to Draw");
}
}
poly.draw();
}
}
This is happening because your myPolygon is null.
Change:
private ArrayList <Point2D.Double> myPolygon;
To this:
private ArrayList <Point2D.Double> myPolygon = new ArrayList<>();
Or, in your constructor, add this line:
myPolygon = new ArrayList<>();
You didn't initialize your ArrayList,
private ArrayList <Point2D.Double> myPolygon;
is equivalent to
private ArrayList <Point2D.Double> myPolygon = null;
so when you say
myPolygon.add(aPoint); // <-- null.add(aPoint);
You could assign it in the constructor, or at declaration (using the List interface and the diamond operator <>) with something like
private List<Point2D.Double> myPolygon = new ArrayList<>();
Related
This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 7 years ago.
I want to be able to store and manage ordered pairs of the
form: (x, y). To solve this problem I created two classes: EuclideanSpace and Point. This is a homework assignment and so it is set up with these specific methods and the class EuclideanSpace and the inner class Point. I thought I had it almost figured out but when I run it it prints out '0' for the x and the y values after the first entry. For every entry after that it prints 'null'.
import java.util.Scanner;
public class EuclideanSpace {
Point point[];
Scanner scanner = new Scanner(System.in);
public EuclideanSpace() {
point = new Point[10];
}// End constructor
// Adds points to the array
public boolean addPoint(int x, int y) {
for (int i = 0; i < 10; i++) {
if (point[i] == null) {
point[i] = new Point();
}// End if
return true;
}// End for
return false;
}// End addPoint
// Prints a point in a given index in the point array
public void printPoint(int i) {
System.out.println(point[i]);
}
// Inner class
public static class Point {
private int x;
private int y;
public void Point(int x, int y) {
this.x = x;
this.y = y;
}// End Point method
public String toString() {
return "X = " + x + "Y = " + y;
}// End toString
}// End inner Class
}// End
Driver class:
import java.awt.Point;
import java.util.Scanner;
public class ICDriver {
static Scanner scanner = new Scanner(System.in);
// New object from the class EuclideanSpace
static EuclideanSpace es = new EuclideanSpace();
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.println("Add point x coordinate? ");
int pointX = scanner.nextInt();
System.out.println("Add point y coordinate? ");
int pointY = scanner.nextInt();
es.addPoint(pointX, pointY);
es.printPoint(i);
} // End for
}// End main
}// End
// Correct your addPoint method
public boolean addPoint(int x, int y) {
for (int i = 0; i < 10; i++) {
if (point[i] == null) {
point[i] = new Point(x,y);
return true;
}// End if
}// End for
return false;
}// End addPoint
//Remove void from your constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}
I'm beginner with programming in Java. I would make an application to count max Point, min Point, width and height. I write in eclipse.
I become this error:
Exception in thread "main" java.lang.NullPointerException
at BoundingBox.height(BoundingBox.java:50)
at App.main(App.java:39)`
and my printed points looks like
Point#659e0bfd
Point#2a139a55
Point#15db9742
How should the method toString looks like in this code?
Point
public class Point {
private double x;
private double y;
public Point(double xnew, double ynew) {
x = xnew;
y = ynew;
}
public double getX() {
return x;
}
public void setX(double xnew) {
x = xnew;
}
public double getY() {
return y;
}
public void setY(double ynew) {
y = ynew;
}
}
BoundingBox
import java.util.List;
public class BoundingBox {
private static Point minPoint;
private static Point maxPoint;
public BoundingBox(List<Point> manyPoints) {
double minX = manyPoints.get(0).getX();
double maxX = manyPoints.get(0).getX();
double minY = manyPoints.get(0).getY();
double maxY = manyPoints.get(0).getY();
for (int i = 0; i < manyPoints.size(); i++) {
Point test = manyPoints.get(i);
test.getX();
if (test.getX() < minX) {
minX = test.getX();
}
if (test.getX() > maxX) {
maxX = test.getX();
}
if (test.getY() < minY) {
minY = test.getY();
}
if (test.getY() > maxY) {
maxY = test.getY();
}
minPoint = new Point(minX, minY);
maxPoint = new Point(maxX, maxY);
}
}
public static double width() {
double a = (maxPoint.getX() - minPoint.getX());
return a;
}
public static double height() {
System.out.println("minPoint = " + minPoint);
System.out.println("maxPoint = " + maxPoint);
double b = (maxPoint.getY() - minPoint.getY());
return b;
}
public Point getMaxPoint() {
return maxPoint;
}
public Point getMinPoint() {
return minPoint;
}
}
Application
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class App {
public static void main(String[] args) {
Point p1 = new Point(10.681,-48.857);
Point p2 = new Point(96.980,20.724);
Point p3 = new Point(66.647,-66.558);
Point p4 = new Point(-2.674,-58.571);
Point p5 = new Point(40.11,-12.342);
Point p6 = new Point(27.782,46.809);
Point p7 = new Point(54.759,-46.709);
Point p8 = new Point(-33.89,-90.787);
Point p9 = new Point(15.84,-67.553);
Point p10 = new Point(19.481,51.331);
List<Point> list1 = new ArrayList<Point>(); // Create ArrayList and add Points
list1.add(p1);
list1.add(p2);
list1.add(p3);
list1.add(p4);
list1.add(p5);
list1.add(p6);
list1.add(p7);
list1.add(p8);
list1.add(p9);
list1.add(p10);
Iterator<Point> itr = list1.iterator( );
while ( itr.hasNext( ) ) {
System.out.println( itr.next( ) );
}
double c = BoundingBox.height();
double d = BoundingBox.width();
System.out.println(" The Points: " + list1 );
System.out.println(" BoundingBox have " + c + "height and" + d + "width." );
System.out.println(" The max Point is " );
System.out.println(" The min Point is " );
}
}
Your variables:
private static Point minPoint;
private static Point maxPoint;
are initialized in BoundingBox constructor, but in your App you don't invoke it, so they are null. Just do the following:
new BoundingBox(list1);
double c = BoundingBox.height();
double d = BoundingBox.width();
and NullPointerException will disappear.
You never created an instance of the BoundingBox class before you tried to call the height() and width() functions so you're a receiving the null pointer exception on the line
double a = (maxPoint.getX() - minPoint.getX());
when it's trying to call maxPoint.getX() and minPoint.getX() since there's no values stored inside the variables
I know the code below is a bit rough , i just need to get it to work before i clean it up. I'm working on newton raphson's methood that repeats as long as a condition is through. here's what i've got so far
import java.util.Scanner;
import static java.lang.System.out;
import static java.lang.System.in;
public class NewtonRaphson {
public static float intervalfunctions(float b){
return ((b*b*b)-3*b+1);
}
public static float differentiatedfunctions(float b) {
return (3*(b*b)-3);
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner myScanner = new Scanner(in);
out.println("PROGRAMME TO SOLVE NEWTON'S SCHEME");
float E, Z, F, D, G,FF,fa,fb,b,fx,ffx,x1;
float x[] = new float[10];
out.println("Enter the accauracy required");
E = myScanner.nextFloat();
out.println("Enter the first Interval");
D = myScanner.nextFloat();
out.println("Enter the final interval");
G = myScanner.nextFloat();
fa = intervalfunctions(D);
fb = intervalfunctions(G);
if ((fa * fb)<0) {
out.println("The Solution exists between the given interval");
x[0] = (D+G)/2;
fx = intervalfunctions(x[0]);
ffx = differentiatedfunctions(x[0]);
x[1] = x[0] - (fx/ffx);
out.println("x[1] is ");
out.print(x[1]);
}
now i need a way to loop x and differentiated functions for the next values where x0 changes to x1 and x1 to x2 on and on to an error tolerance of 10^-2. i know i'll definitely need a while loop and maybe a for loop , but i need a way to loop through my x array .. i couldnt do this for (x[1++]) . i'll also need a way to loop my methods for each new value of x.
I can't say I'm following what you are trying to calculate, but if I understood your explanation, you need a loop similar to this :
x[0] = (D+G)/2;
fx = intervalfunctions(x[0]);
ffx = differentiatedfunctions(x[0]);
for (int i = 1; i < 10; i++) {
x[i] = x[i-1] - (fx/ffx);
fx = intervalfunctions(x[i]);
ffx = differentiatedfunctions(x[i]);
}
I have been developing an implementation of the neighbourhood algorithm in Java for a physics project I am working on. I'm brand new to Java so I apologize for any idiocy that results.
I have been getting the error
''
incompatible types
found : void
required: java.util.List<VoronoiPoint>
'' on line 22 from the Java compiler in attempting to compile the program shown below. I cannot figure out why the variable ''thelist'' somehow turns into a void when I declared it to be of type List<VoronoiPoint>. If anybody can explain to me what is going on it would be much appreciated!
import java.lang.Double;
import java.util.*;
public class VoronoiTiling
{
public static void main(String args[])
{
Integer n = 10; //Number of dimensions of model parameter space
Integer ns = 20; //Number of points per iteration
Integer nr = 4; //Number of cells to populate
Integer iterations = 5; //Number of iterations
List<VoronoiPoint> thelist = VoronoiList.startlist(ns,n);
//System.out.println(thelist);
//System.out.println(thelist.get(1).misfit);
for (Integer i=0 ; i<thelist.size() ; i++)
{
thelist.get(i).setmisfit();
}
List<VoronoiPoint> orderedlist = Collections.sort(thelist);
Double distance = EuclidianDistance((thelist.get(1)).location,(thelist.get(2)).location);
System.out.println(distance);
}
public static Double EuclidianDistance(Double[] point1, Double[] point2)
{
Double distance=0.0;
for (int i = 0; i < point1.length; i++)
{
distance = distance + Math.pow((point1[i]-point2[i]),2);
}
return Math.sqrt(distance);
}
}
The other classes I used are here:
The VoronoiList class:
import java.util.*;
public class VoronoiList
{
public static List<VoronoiPoint> startlist(Integer ns, Integer n)
{
List<VoronoiPoint> thestartlist = new ArrayList<VoronoiPoint>();
for (int i = 0; i < ns; i++)
{
thestartlist.add(new VoronoiPoint(0.,n));
}
return thestartlist;
}
}
The VoronoiPoint class:
import java.util.Random;
public class VoronoiPoint implements Comparable<VoronoiPoint>
{
Double[] location;
private Random generator = new Random();
Double misfit = -1.;
//***************************************************************
public VoronoiPoint(Double misfit, Integer n)
{
location = new Double[n];
ParameterBoundaries boundaries = new ParameterBoundaries(n);
for(int i = 0; i < n; i++)
{
location[i] = boundaries.getboundaries(2*i)+2*generator.nextDouble();
}
}
//***************************************************************
//public Double[] getlocation()
//{
//return location;
//}
public void setlocationi(Integer i, Double j)
{
location[i] = j;
}
//***************************************************************
public void setmisfit()
{
Integer n = location.length;
Double tempmisfit = 0.0;
for(Integer i = 0; i < n; i++)
{
tempmisfit = tempmisfit + Math.pow((location[i]),2);
}
misfit = Math.sqrt(tempmisfit); // Temporarily just distance to centre
}
//public Double getmisfit()
//{
//return misfit;
//}
public int compareTo(VoronoiPoint b)
{
if (this.misfit<b.misfit) return -1;
else if (this.misfit==b.misfit) return 0;
return 1;
}
}
And the parameter boundaries class:
public class ParameterBoundaries
{
private Double[] boundaries; /*Set to 2n where n is dimensions of parameter space,
* it just makes it easier*/
public ParameterBoundaries(Integer n)
{
boundaries = new Double[2*n];
for(Integer i = 0; i<n; i++)
{
boundaries[2*i] = -1.0;
boundaries[2*i+1] = 1.0;
}
}
public Double getboundaries(Integer i)
{
return boundaries[i];
}
}
Collections.sort(..) sorts the original list. It doesn't return a new list. (Its return type is void)
Your code is wrong. Collections.sort() is an in-place sort function; it modifies the given list argument and returns nothing (void).
I'm using the Point Class to manage a list of (x,y) coordinates and I need to sort them in order of X.
I read online to make a new class PointCompare that implements Comparator, however I'm not sure how this works and therefore I have a compiler error in the sortByXCoordinates method.
Help would be appreciated a lot, and any comments are welcome, thanks in advance.
Here is some of my code:
import javax.swing.JOptionPane;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
//import java.util.Iterator;
public class ConvexHullMain {
private Point coordinates = new Point(0, 0);
private final int MAX_POINTS = 3;
private ArrayList<Point> coordinateList = new ArrayList<Point>();
public void inputCoordinates() {
String tempString; // temp string for JOptionPane
int tempx = 0;
int tempy = 0;
for (int i = 0; i < MAX_POINTS; i++) {
try {
// input x coordinates
tempString = JOptionPane.showInputDialog(null,
"Enter X coordinate:");
tempx = Integer.parseInt(tempString);
// input y coordinates
tempString = JOptionPane.showInputDialog(null,
"Enter Y coordinate:");
tempy = Integer.parseInt(tempString);
coordinates.setLocation(tempx, tempy);// set input data into
// coordinates object
coordinateList.add(coordinates.getLocation()); // put in
// arrayList
} // end Try
catch (NumberFormatException e) {
System.err.println("ERROR!");
main(null);
} // end catch
}// end for loop
}
public void displayPoints() {
for (int i = 0; i < MAX_POINTS; i++) {
JOptionPane.showMessageDialog(null, "Point number " + (i + 1)
+ " is: " + coordinateList.get(i));
}
// alt method
// Iterator i = coordinateList.iterator();
// String outputTemp;
// while (i.hasNext()) {
// outputTemp = i.next().toString();
// JOptionPane.showMessageDialog(null, "Point number " + " is: "
// + outputTemp);
// }
}
/**
* This sorts the points by the X coordinates
*/
public void sortByXCoordinates(){
coordinateList.sort(coordinates, new PointCompare());
}
public class PointCompare implements Comparator<Point> {
public int compare(Point a, Point b) {
if (a.x < b.x) {
return -1;
} else if (a.x > b.x) {
return 1;
} else {
return 0;
}
}
}
public static void main(String[] args) {
ConvexHullMain main = new ConvexHullMain();
main.inputCoordinates();
main.displayPoints();
}
}
private ArrayList<Point> coordinateList = new ArrayList<Point>();
...
Collections.sort(coordinateList, new PointCompare());
...
public class PointCompare implements Comparator<Point> {
public int compare(Point a, Point b) {
if (a.x < b.x) {
return -1;
}
else if (a.x > b.x) {
return 1;
}
else {
return 0;
}
}
}
You were close. The problem you had was simply that you invoked
public void sortByXCoordinates(){
coordinateList.sort(coordinates, new PointCompare());
}
What you want is this:
import java.awt.Point;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import javax.swing.JOptionPane;
public class MainClass {
private final Point coordinates = new Point(0, 0);
private final int MAX_POINTS = 3;
private final ArrayList<Point> coordinateList = new ArrayList<Point>();
public void inputCoordinates() {
String tempString;
int tempx = 0;
int tempy = 0;
for (int i = 0; i < this.MAX_POINTS; i++) {
try {
tempString = JOptionPane.showInputDialog(null, "Enter X coordinate:");
tempx = Integer.parseInt(tempString);
tempString = JOptionPane.showInputDialog(null, "Enter Y coordinate:");
tempy = Integer.parseInt(tempString);
this.coordinates.setLocation(tempx, tempy);// set input data into
this.coordinateList.add(this.coordinates.getLocation()); // put in
}
catch (final NumberFormatException e) {
System.err.println("ERROR!");
main(null);
}
}
}
public void displayPoints() {
for (int i = 0; i < this.MAX_POINTS; i++) {
JOptionPane.showMessageDialog(null, "Point number " + (i + 1) + " is: " + this.coordinateList.get(i));
}
}
/**
* This sorts the points by the X coordinates
*/
public void sortByXCoordinates() {
Collections.sort(this.coordinateList, new PointCompare());
}
public class PointCompare
implements Comparator<Point> {
public int compare(final Point a, final Point b) {
if (a.x < b.x) {
return -1;
}
else if (a.x > b.x) {
return 1;
}
else {
return 0;
}
}
}
public static void main(final String[] args) {
final MainClass main = new MainClass();
main.inputCoordinates();
main.displayPoints();
}
}
i'm going to ignore all of the code you posted because you've just dumped everything without taking the time to identify the relevant areas.
now, from your question: you have an ArrayList containing Points. You want to sort it by the X axis/value.
List<Point> list = new ArrayList<Point>();
Firstly you need a Comparator which will compare one Point to another.
Comparator<Point> comp = new Comparator<Point>()
{
#Override
public int compare(Point o1, Point o2)
{
return new Integer(o1.x).compareTo(o2.x);
}
};
I choose to "box" the int to an Integer and use Integer's compareTo method. You could come up with a tidier method of comparison, up to you.
Then you can use the utility method Collections.sort
Collections.sort(list, comp);
and your list is sorted.
I'm using the Point Class to manage a list of (x,y) coordinates and I need to sort them in order of X
You can use a Bean Comparator or a custom Comparator as described in the blog.
The ArrayList class (see API documentation: http://download.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html) that you use for your 'coordinateList' does not have a sort() method. You will have to implement this yourself, or use Collections.sort().