2 Java方法显示java.lang.NullPointerException [英] 2 Java methods java.lang.NullPointerException

查看:177
本文介绍了2 Java方法显示java.lang.NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我米以下code得到一个错误显示java.lang.NullPointerException错误。

的算法:

  1. 如果N≤3找到最接近的点用暴力和​​停止。
  2. 找到的垂直线V,使得将输入设定成两个不相交的子集PL与尺寸的PR尽可能相等。指向左侧或上线属于PL及指向右侧或上线属于PR。没点同时属于自集是不相交的。
  3. 递归找到接近的一对点的PL的距离δL和的距离的接近的δR 对公关。
  4. 让δ=分钟(δL,δR)。一对接近的点,在输入设定P的距离可以是,在递归步骤中找到的点(即,δ)或由在PL一个点和在PR的点之间的距离的。
    1. 的唯一候选点1从PL与一个来自PR必须在垂直条组成 一行在距离δ的线V的左侧和线在距离δ为V的权
    2. 让YV是点带排序非递减y坐标内的数组 (即,如果我≤Ĵ然后YV [I]≤YV [J])。
    3. 在开始与YV第一点和步进低谷所有除最后,检查该点的距离,下一个7分(或任何被留下,如果有不多达7)。如果对被发现的距离比严格δ小于分配这个距离δ。
  5. 返回δ

底线是,它使用一个概念性的扫描线和递归来找到最接近点的欧几里得空间

我有写

现在的方法:

  • 公共静态INT CP(点集P)。

    这的确方法算法的递归部分的preparatory工作,并调用方法closestPairAux的递归部分。

  • 公共静态INT CPA(点[] X,点[] Y)。 此方法执行该算法的递归部分;也就是说,大量的工作。

其他的方法和类

一个点再由Point类的一个对象psented在飞机$ P $。这确实显而易见的事情;它拥有x和y坐标的数字,这样如果P型指向的对象,然后过氧化物酶和芘

一组输入点的重新由类点集的对象psented $ P $。因为这是 一组就不可能有重复一个观点,我们不能假设上的元素任何排序。

  • 公共静态点集g第(字符串F)。

    这将打开一个所谓的F文件,并​​从中读取点。

  • 公共点NP(点集P)。

    这是用于迭代中P.算法 closestPair <​​/ code>由法实施

  • 公共静态点closestPair(点集P)。

    1. 如果N = 2,则返回(X1 - X2)^ 2 +(Y1 - Y2)^ 2
    2. 其他
    3. ð←0
    4. 对于我←1到n - 1做
    5. &NBSP;&NBSP;对于j←I + 1到n做
    6. &NBSP;&NBSP;&NBSP;&NBSP;牛逼←(十一 - XJ)^ 2 +(YI - YJ)^ 2
    7. &NBSP;&NBSP;&NBSP;&NBSP;如果T&LT; ð那么
    8. &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP; d←牛逼
    9. 返回ð
  • 公共静态点集generatePoints(INT N)。

    这将返回一组n个点,其坐标是整数。

  • 公共点[]排序(字符C)。

    这将返回点的点阵列中的排序设置通过坐标由参数C所示非递减顺序。此参数的值或者是'X'和值'Y',一个异常UnknownSortOptionException引发除外。

这是我写的,到目前为止:

我决定,第一种方法应该做琐碎的情况下,N =&LT; 3,然后调用辅助方法

 公共静态INT CP(点集P)
        抛出TrivialClosestPairException,UnknownSortOptionException
{
           INT距离= 0; //方法形成计算这点和其他点之间的距离平方的Poirnt类
           点[]×= P.sort('×');
    点[]×= P.sort('Y');

        距离= CPA(X,Y); **  - &gt;此处**

    返回的距离;

}
 

的定义,因为它应该这个方法?

的第二个:我需要在这一个大的时间帮助

 公共静态INT CPA(点[] X,点[] Y)
        抛出TrivialClosestPairException,UnknownSortOptionException
{
    如果(X.length 4;){
         返回PointSet.nCP(新点集(X));

 }

    INT V = X [(int)的Math.ceil(((双)X.length / 2)-1)〕的getX()。


    点[] PL = Arrays.copyOfRange(X,(int)的0,(int)的Math.ceil(X.length / 2));
    点[] PR = Arrays.copyOfRange(X,(int)的Math.floor(X.length / 2),(int)的X.length-1);


     INT距离= Math.min(CPA(PL,Y)cPAPR,Y)); **  - &gt;此处**

    点[] shortDist =新点[Y.length]


       INT N = 0;


     的for(int i = 0; I&LT; Y.length;我++)
{

     INT A = Y [I] .getY();
      如果((V-A)×(V-A)&LT; =距​​离)
  {

   shortDist [N] = Y [I]

       }
    }


    的for(int i = 0; I&LT; shortDist.length -1;我++)
   {


  对于(INT R = I + 1; R&LT; shortDist.length-1和;&功放;为r I + 7; R ++){
     距离= Math.min(D,shortDist [I] .sqrDist(shortDist [R])); **  - &gt;此处**

 }
  }

 返回距离; **  - &gt;此处**

 }
 

现在,当我定义了下面的类来测试我的方法

 公共类测试{
公共静态无效的主要(字串[] args)
 {
   ClosestPair.closestPairCheck(10,10);
 

//生成大小为n点的T台,并获得了一个所声称最近的平方距离    对使用实施方法closestPair每套。如果所有的结果    是否正确则消息报告,这是返回,报道别人的失败。没有进一步的    给出的信息。需要注意的是T必须是严格正(异常Invalid- NumberOfTestsException引发其他方式)。      }     }

我得到下面的异常线程main显示java.lang.NullPointerException在3点的时候,我给可变距离值(我上面注吧)......我该怎么办?

解决方案

好吧,让我们看看你的code。首先,一个小提示:为code被张贴在计算器(和其他stackexchange网站)更好地利用仅供缩进空格,因为标签看起来不是那么糟糕

所以,在这里你的code再次,适当的缩进(用Emacs,同时JDEE的方式做到了 - 看起来像我没有配置正确,或者它有一些问题搞清楚你的​​code)和我的意见穿插。

 公共静态INT closestPairAux(点[] X,点[] Y)
 

所以,问题又来了:什么是这两个参数数组的含义?难道它们都含有同一个点,或其他的吗?你为什么让两个数组?当你已经回答了这个,给他们更好的名字。

除了这个,给你的方法的文档注释。它接受什么样的参数,这是什么回报? (不退还的距离,但这种距离的平方,如果我理解正确的。)

 抛出TrivialClosestPairException,UnknownSortOptionException
{
    如果(X.length 4;){
        返回PointSet.naiveClosestPair(新点集(X));
    }
 

好了,在这里你有递归的小数组的结束。

  INT V = X [(INT)Math.ceil(((双)X.length / 2)-1)的getX()。
 

如果我理解正确的,你想获取数组的中间元素在这里。这样会更清晰:

  INT middleIndex = X.length / 2;
INT V = X [middleIndex] .getX();
 

在Java中,整数除法的工作方式是舍入向零 - 这样的 middleIndex 的长度为20或21的阵列是两个10。(如果你想让它是9在第一种情况下,分前减1。)

当然,你可以把它写成 INT V = X [X.length / 2] .getX(); ,但是你可以使用 middleIndex 接下来的两个语句

 点[] PL = Arrays.copyOfRange(X,(INT)0,(INT)Math.ceil(X.length / 2));
    点[] PR = Arrays.copyOfRange(X,(int)的Math.floor(X.length / 2),(int)的X.length-1);
 

至于说,重写这两个使用 middleIndex 和以前一样。你也不需要转换 0 X.length-1 来诠释,他们已经是。 (而又有看看Arrays.copyOfRange的文档 - 的指数是唯一的)

所以,在这里要拆分你的X阵列分为两(约)相同大小的数组,没关系。

  INT距离= Math.min(closestPairAux(PL,Y),closestPairAux(PR,Y));
 

下面是你的递归调用。你在这里做什么,其实?你为什么要递归调用给这些参数? (特别的,为什么都接收相同的Y阵列?

 点[] shortDist =新点[Y.length]

    INT N = 0;
    的for(int i = 0; I&LT; Y.length;我++)
        {
            INT A = Y [I] .getX();
            如果((V-A)×(V-A)&LT; =距​​离)
                {
                    shortDist [N] = Y [I]
                }
        }
 

所以,现在你要通过你的Ÿ阵列,收集那些靠近的分隔您的新 shortDist -array。

元素

 的for(int i = 0; I&LT; shortDist.length -1;我++)
        {
            对于(INT R = I + 1; R&LT; shortDist.length-1和;&功放;为r I + 7; R ++){
                D = Math.min(D,shortDist [I] .sqrDist(shortDist [R]));
            }
        }
 

D 一样的距离过吗?

 返回D组;
}
 

目前所有的,它看起来像你的算法的实现,是的。想一下我的问题,并请至少在code运行一个编译器,以确保它不会有一些明显的语法错误(通过拼写错误)。 在code添加在适当的地方(的code块前)的意见,并测试你的算法对于一些(可能是随机的)例如输入,比较它的的幼稚的实施(他们应该同时返回相同的结果,但你的一个是希望更快。)

I"m getting an error java.lang.NullPointerException error on the following code.

The algorithm:

  1. If n ≤ 3 find the closest points by brute force and stop.
  2. Find a vertical line V such that divides the input set into two disjoint subsets PL and PR of size as equal as possible. Points to the left or on the line belong PL and points to the right or on the line belong to PR. No point belongs to both since the sets are disjoint.
  3. Recursively find the distance δL of a closest pair of points in PL and the distance δR of a closest pair in PR.
  4. Let δ = min(δL, δR). The distance of a pair of closest points in the input set P is either that of the points found in the recursive step (i.e., δ) or consists of the distance between a point in PL and a point in PR.

    1. The only candidate points one from PL and one from PR must be in a vertical strip consisting of a line at distance δ to the left of the line V and a line at distance δ to the right of V
    2. Let YV be an array of the points within the strip sorted by non-decreasing y coordinate (i.e., if i ≤ j then YV [i] ≤ YV [j]).
    3. Starting with the first point in YV and stepping trough all except the last, check the distance of this point with the next 7 points (or any that are left if there are not as many as 7). If a pair is found with distance strictly less than δ then assign this distance to δ.

  5. Return δ.

Bottom line is that,it uses a conceptual sweep line and recursion to find the closest points in the Euclidean space.

Now the methods that I have to write:

  • public static int cP(pointSet P).

    This does methods the preparatory work for the recursive part of the algorithm and calls the method closestPairAux for the recursive part.

  • public static int cPA(Point [] X, Point [] Y). This method carries out the recursive part of the algorithm; that is, the bulk of the work.

Other methods and classes

A point is represented in the plane by an object of the class Point. This does the obvious thing; it holds the x and y coordinates as numbers so that if P is an object of type Point then P.x and P.y

The set of input points is represented by an object of the class PointSet. As this is a set there can be no repetition of a point and we cannot assume any ordering on the elements.

  • public static PointSet gP(String f).

    This opens a file called f and reads points from it.

  • public Point nP(PointSet P).

    This is used to iterate over the points in P. The algorithm closestPair is implemented by the method

  • public static Point closestPair(PointSet P).

    1. if n = 2 then return (x1 − x2)^2 + (y1 − y2)^2
    2. else
    3. d ← 0
    4. for i ← 1 to n − 1 do
    5.    for j ← i + 1 to n do
    6.      t ← (xi − xj)^2 + (yi − yj)^2
    7.      if t < d then
    8.       d ← t
    9. return d

  • public static PointSet generatePoints(int n).

    This returns a set of n points, whose coordinates are integers.

  • public Point[] sort(char c).

    This returns the points in the point set in an array sorted in non-decreasing order by coordinate as indicated by the parameter c. This parameter takes either the value ’x’ or the value ’y’, an exception UnknownSortOptionException is raised otherwise.

This what I wrote so far:

I decide that the first method should do the trivial case,n=<3, and then call the aux method.

  public static int cP(PointSet P) 
        throws TrivialClosestPairException, UnknownSortOptionException
{
           int distance = 0;// a method form the Poirnt class that calculate the square                              distance between this point and another point
           Point[] x = P.sort('x');
    Point[] x = P.sort('y');

        distance = cPA(x, y); **->here**

    return distance;

}

Is this method defined as it should?

An the second one: Which I need big time help on this one.

public static int cPA(Point[] X, Point[] Y) 
        throws TrivialClosestPairException, UnknownSortOptionException
{
    if (X.length<4){
         return PointSet.nCP(new PointSet (X));

 }

    int V = X[(int) Math.ceil(( (double) X.length/2)-1)].getX();


    Point[] PL = Arrays.copyOfRange(X,(int) 0,(int) Math.ceil(X.length/2));
    Point[] PR = Arrays.copyOfRange(X,(int) Math.floor(X.length/2), (int) X.length-1);


     int distance = Math.min(cPA(PL,Y),cPAPR,Y));**->here**

    Point[] shortDist = new Point[Y.length];


       int n = 0;


     for (int i = 0; i <Y.length; i++)
{

     int A = Y[i].getY();
      if ((V-A)*(V-A) <= distance)
  {

   shortDist[n] = Y[i];

       }
    }


    for (int i =0; i< shortDist.length -1; i++)
   {


  for (int r = i+1; r <shortDist.length-1 && r< i + 7; r ++){
     distance = Math.min(d, shortDist[i].sqrDist(shortDist[r]));**->here**

 }
  }

 return distance;**->here**

 }

Now when I define the following class to test my methods

     public class Test{
public static void main(String [ ] args)
 {
   ClosestPair.closestPairCheck( 10, 10);

//Generates t sets of points of size n and obtains the squared distance of a claimed closest pair using your implementation of the method closestPair for each set. If all results are correct then a message reporting this is returned, else failure is reported. No further information is given. Note that t must be strictly positive (an exception Invalid- NumberOfTestsException is raised otherwise). } }

I get the following Exception in thread "main" java.lang.NullPointerException in the 3 spots when I give the variable distance values(I note it above)...What should I do?

解决方案

Okay, lets have a look at your code. First, a small hint: for code to be posted on stackoverflow (and other stackexchange sites) better use only spaces for indentation, since tabs look bad.

So, here your code again, properly indented (by the way Emacs with JDEE did it - looks like I didn't configure it right, or it had some problems figuring out your code), and with my comments interspersed.

public static int closestPairAux(Point[] X, Point[] Y) 

So, again the question: what are the meanings of those two parameter arrays? Are they both containing the same points, or other ones? Why are you giving both arrays? When you have answered this, give them better names.

Other than this, give your method a documentation comment. What arguments does it receive, what does it returns? (It does not return the distance, but the square of the distance, if I understand right.)

    throws TrivialClosestPairException, UnknownSortOptionException
{
    if (X.length<4){
        return PointSet.naiveClosestPair(new PointSet (X));
    }

Okay, here you have the end of recursion for small arrays.

    int V = X[(int) Math.ceil(( (double) X.length/2)-1)].getX();

If I understand right, you are trying to get the middle element of the array here. This way would be clearer:

int middleIndex = X.length/2;
int V = X[middleIndex].getX();

In Java, integer division works by rounding-towards-zero - so the middleIndex for an array of length 20 or 21 is both 10. (If you want it to be 9 in the first case, subtract 1 before dividing.)

Of course you could write it as int V = X[X.length/2].getX();, but you'll be able to use the middleIndex again in the next two statements.

    Point[] PL = Arrays.copyOfRange(X,(int) 0,(int) Math.ceil(X.length/2));
    Point[] PR = Arrays.copyOfRange(X,(int) Math.floor(X.length/2), (int) X.length-1);

As said, rewrite those two using the middleIndex as before. You also don't need to cast 0 and X.length-1 to int, they already are. (And have again a look at the documentation of Arrays.copyOfRange - the to index is exclusive.)

So, here you are splitting your X array into two (about) same-sized arrays, okay.

    int distance = Math.min(closestPairAux(PL,Y),closestPairAux(PR,Y));

Here is your recursive call. What are you doing here, in fact? Why are you giving these parameters to the recursive call? (Specially, why do both receive the same Y array?)

    Point[] shortDist = new Point[Y.length];

    int n = 0;
    for (int i = 0; i <Y.length; i++)
        {
            int A = Y[i].getX();
            if ((V-A)*(V-A) <= distance)
                {
                    shortDist[n] = Y[i];
                }
        }

So, now you are going through your Y array, collecting those elements which are near the divider in your new shortDist-array.

    for (int i =0; i< shortDist.length -1; i++)
        {
            for (int r = i+1; r <shortDist.length-1 && r< i + 7; r ++){
                d = Math.min(d, shortDist[i].sqrDist(shortDist[r]));
            }
        }

Is d the same as distance before?

    return d;
}

At all, it looks like an implementation of your algorithm, yes. Think a bit about my questions, and please at least run a compiler on the code to make sure it does not have some evident syntax errors (through typos). Add comments in your code at the right places (before a block of code), and test your algorithm for some (maybe random) example inputs, comparing it to the naive implementation (they should return both the same result, but your one is hopefully faster.)

这篇关于2 Java方法显示java.lang.NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆