Я думаю, что мой rsort()
метод должен работать правильно, я всегда получаю исключение:
In Thread "main": java.lang.NullPointerExeception
at IntQueue.get(IntQueue.java:47)
at V5.main(V5.java:88)
Почему я получаю это исключение и как я могу его обработать?
IntQueue.java:
class IntQueue
{
public int get()
{
int res = fyrsti.tala; // <---- this is line 47 -----
n--;
if( fyrsti == sidasti )
fyrsti = sidasti = null;
else
fyrsti = fyrsti.naest;
return res;
}
static class Hlekkur
{
int tala;
Hlekkur naest;
}
Hlekkur fyrsti;
Hlekkur sidasti;
int n;
public IntQueue()
{
fyrsti = sidasti = null;
}
public int first()
{
return fyrsti.tala;
}
public void put( int i )
{
Hlekkur nyr = new Hlekkur();
n++;
nyr.tala = i;
if( sidasti==null )
fyrsti = sidasti = nyr;
else
{
sidasti.naest = nyr;
sidasti = nyr;
}
}
public int count()
{
return n;
}
}
V5.java:
public class V5
{
public static void main(String [] args)
{
IntQueue q = new IntQueue();
Random rand = new Random();
for(int i = 0; i!= 10000; i++)
q.put(rand.nextInt(1000));
q = rsort(q);
int last = q.get(); // <---- this is line 88 -----
while(q.count() != 0)
{
int x = q.get();
if(x < last)
System.out.println("Wrong");
System.out.println("Right");
last = x;
}
}
public static IntQueue rsort(IntQueue q)
{
IntQueue [] r = new IntQueue[10];
for(int i = 0; i!=10; i++)
r[i] = new IntQueue();
IntQueue q2 = q;
int i = 0, v=1;
while(i != 3)
{
while(q2.count() != 0)
{
int x = q.get();
r[(x/v)%10].put(x);
}
for(int j = 0; j!=0; j++)
{
if(r[j].count() != 0)
q2.put(r[j].get());
else
j++;
}
v *= 10;
i++;
}
return q2;
}
}
[под ред. примечание: переупорядоченный и сжатый код, чтобы сделать соответствующие строки более заметными]