请帮我弄清楚空指针异常。我无法理解哪个变量或对象是null。我能解决它吗?
package coll.org;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Scanner;
public class SnakeAndladder1 {
ArrayList<String> name1=new ArrayList<String>(); //an array to store players names
public int throwdice() //to calculate the dice value
{
return (int)(Math.random()*6)+1;
}
public int ladder(int curscore)
{
Hashtable ld = new Hashtable();
ld.put(15,30);
ld.put(45,71);
ld.put(25,62);
ld.put(81,91);
ld.put(9,39);
Object v=ld.get(curscore);
return (int)v;
}
public int snake(int curscore)
{
Hashtable ld = new Hashtable();
ld.put(29,11);
ld.put(81,48);
ld.put(30,6);
ld.put(92,71);
ld.put(58,19);
Object v=ld.get(curscore);
return (int)v;
}
public boolean Game (String name1){
int score=0;
String name;
int v=0;
name=name1.toString();
System.out.println("Click y to roll dice");
Scanner in2=new Scanner(System.in);
String yes=in2.nextLine();
if(yes.equalsIgnoreCase("y"))
{
v=throwdice();
System.out.println("dice value:"+v);
}
score=score+v;
if(score==100)
{
System.out.println("User:"+name+"got"+v+".Winner!!!");
return false;
}
if (score>100)
{
score=score-v;
System.out.println("Current score of"+name+"is"+score);
return true;
}
int s1=ladder(score);
if(s1==score)
{
score=snake(score);
System.out.println("Current score of"+name+"is"+score);
return true;
}
else
{
score=s1;
System.out.println("Current score of"+name+"is"+score);
return true;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int l=0;
boolean flag=true;
System.out.println("Enter the number of players:");
Scanner in=new Scanner(System.in);
int n=in.nextInt();
System.out.println("Enter Players names in order:");
ArrayList<String> name1=new ArrayList<String>(); //an array to store players names
for (int i=0;i<n;i++)
{
Scanner in1=new Scanner(System.in);
String name2=in1.nextLine();
name1.add(name2);
}
SnakeAndladder1 players[];
players = new SnakeAndladder1[n];
while(flag)
{
while(l<n)
{
flag = players[l].Game(name1.get(l)); //----Error occuring here.Its a null pointer
} exception
}
}
}
堆栈跟踪是:
Enter the number of players:
3
Enter Players names in order:
raghav
kishan
sr
Exception in thread "main" java.lang.NullPointerException
at coll.org.SnakeAndladder1.main(SnakeAndladder1.java:107)
答案 0 :(得分:3)
以下使用n
nulls初始化数组:
players = new SnakeAndladder1[n];
要避免使用NPE,您需要在调用Game()
之前创建对象。
答案 1 :(得分:1)
SnakeAndladder1 players[];
players = new SnakeAndladder1[n];
在上面添加:
for(int i = 0; i < players.length; i++)
{
players[i] = new SnakeAndladder1();
}
这将初始化数组中每个元素的对象。
答案 2 :(得分:0)
您的案例中的n
为空,因为您从用户那里获取了值。因此它不会将数组创建为有限数组。他们都是空的。
尝试首先从用户初始化数字,然后初始化数组。