這是我爲蛇和階梯寫的代碼。請幫助我解決例外問題。例外情況在第72和114行。我已經突出顯示了導致異常的評論。感謝提前尋求幫助。如何解決java.lang.NullPointerException?
package practical1;
import java.io.Console;
import java.util.ArrayList;
import java.util.Scanner;
public class snakeandladder1 {
int totalpos=100;
int v=0;
int[] scores;
int score=0;
int l=0;
public int throwdice()
{
int i=0;
{
while(i==0)
{
i=(int)Math.random()*100;
i=i%13;
}
return i;
}
}
public int ladder(int score)
{
if(score==15)
score=30;
else if(score == 45)
score=71;
else if(score == 25)
score=62;
else if(score == 81)
score=91;
else if(score == 9)
score=39;
scores[l]=score;
return score;
}
public int snake(int score)
{
if(score == 29)
score=11;
else if(score == 81)
score=48;
else if(score == 92)
score=71;
else if(score == 30)
score=6;
else if(score == 58)
score=19;
scores[l]=score;
return score;
}
void start()
{
System.out.println("Enter the number of players:");
Scanner in=new Scanner(System.in);
int n=in.nextInt();
in.close();
l=n;
System.out.println("Enter Players names in order:");
ArrayList<String> name1=new ArrayList<String>();
for (int i=0;i<n;i++)
{
Console in1=System.console();
String name2=in1.readLine(); //---- I am getting this null pointer exception here.
name1.add(name2);
}
while(true)
{
while(l>0)
{
System.out.println("Click y to roll dice %d"+(l+1));
Console in2=System.console();
String yes=in2.readLine();
if (yes == "y")
{
v=throwdice();
}
score = scores[l]+v; ((//--- the null pointer exception after changing all user input to scanner))
if(score==totalpos)
{
System.out.println("User:"+name1.get(l)+" got "+v+".Winner!!!");
break;
}
else if(score > totalpos)
{
scores[l]=scores[l];
}
int s1;
s1=ladder(score);
if(s1==score)
{
snake(score);
}
System.out.println("Current score of"+name1.get(l)+"is:"+scores[l]);
l--;
}
if(l==0)
{
l=n;
}
}
}
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
snakeandladder1 sal=new snakeandladder1(); ((//null pointer exception here as well after the changes))
sal.start(); //------ i am getting this null pointer exception here
}
}
嘗試'新的掃描儀(System.in)'讀取從標準輸入流的輸入。閱讀[JavaDoc](http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#console%28%29) - *返回與當前Java虛擬相關的唯一控制檯對象機器,如果有的話,否則'空'。* – Braj 2014-10-10 18:43:07
你能分享你的完整堆棧跟蹤嗎? – Mureinik 2014-10-10 18:44:45
爲什麼你同時使用'in'和'in1'?兩個對象基本相同(從控制檯輸入)...使用'in'並放棄'in1' – Barranka 2014-10-10 18:45:16