在 Java 中捕获 nullpointerexception [已关闭]
2022-09-01 15:01:33
我尝试使用try-catch块来捕获,但以下程序仍然给出错误。我是否做错了什么,或者有没有其他方法可以在以下程序中捕获。任何帮助都非常感谢。NullPointerException
NullPointerException
public class Circular_or_not
{
/**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
try
{
LinkedListNode[] nodes = new LinkedListNode[10];
for (int i = 0; i < 10; i++)
{
nodes[i] = new LinkedListNode(i, null, i > 0 ? nodes[i - 1] : null);
}
// Create loop;
// nodes[9].next = nodes[3];
Boolean abc= Check_Circular(nodes[0]);
System.out.print(abc);
}
catch(NullPointerException e)
{
System.out.print("NullPointerException caught");
}
}
public static boolean Check_Circular(LinkedListNode head)
{
LinkedListNode n1 = head;
LinkedListNode n2 = head;
// Find meeting point
while (n2.next != null)
{
n1 = n1.next;
n2 = n2.next.next;
if (n1 == n2)
{
return true;
}
}
return false;
}
}