我正在嘗試做一個for循環,它使得我有1000個對象並將它們放置到隨機生成的點(x,y)。所以這裏是代碼。我一直在掙扎着這麼多個小時,我也一直在網上尋找,但還沒有找到任何方法來做到這一點。在這個循環之後,我嘗試將這些物體添加到某種雷達中。如何從循環中獲取變量
下面的代碼(所以問題是,我無法弄清楚如何採取變量從循環,使其出現在循環外):
case "look": {
System.out.print("You are at: " +px +", " +py);
System.out.println("");
StringBuilder objects = new StringBuilder(); //That's something i found out form the net..
while (objnum>=0){ objnum--; //Creates randomly 1000objects around the map
int objid = (int)(Math.random() * 11 + 1); //int objnum is 1000, told above
int objx = (int)(Math.random() * 10000 + 1);
int objy = (int)(Math.random() * 10000 + 1);}
board.spawnObject(new BoardObject(objectid, objx, //That's something i found out form the net..
objy, objnum));
for(int x=px-2 ; x< px+3 ; x++){ //px=player position
for(int y=py-2 ; y< py+3 ; y++){ //this is how radar is created
if(objid==1 && x==objx && y==objy){board[x][y]=1;}
else if(objid==2 && x==objx && y==objy){board[x][y]=2;}
else if(objid==3 && x==objx && y==objy){board[x][y]=3;} //That's where i need info from the loop..
else if(objid==4 && x==objx && y==objy){board[x][y]=4;}
else if(objid==5 && x==objx && y==objy){board[x][y]=5;}
else if(objid==6 && x==objx && y==objy){board[x][y]=-1;}
else if(objid==7 && x==objx && y==objy){board[x][y]=-2;}
else if(objid==8 && x==objx && y==objy){board[x][y]=-3;}
else if(objid==9 && x==objx && y==objy){board[x][y]=-4;}
else if(objid==10 && x==objx && y==objy){board[x][y]=-5;}
if(x==px && y==py){
board[x][y]=6;}//<- this shows players position on radar
if(board[x][y]==-1){
System.out.print("[sto]");
}else if(board[x][y]==0){
System.out.print("[___]");//<- This works well..
}else if(board[x][y]==-2){
System.out.print("[box]");
}
else if(board[x][y]==-3){
System.out.print("[ppl]");
}
else if(board[x][y]==-4){
System.out.print("[pit]");
}
else if(board[x][y]==-5){
System.out.print("[brk]");
} //That's how radar shows dots/objects
else if(board[x][y]==1){
System.out.print("[kid]");
}
else if(board[x][y]==2){
System.out.print("[tre]");
}
else if(board[x][y]==3){
System.out.print("[pet]");
}
else if(board[x][y]==4){
System.out.print("[bus]");
}
else if(board[x][y]==5){
System.out.print("[???]");
}
else if(board[x][y]==6){
System.out.print("[You]");} //<- This works well..
}
System.out.println();
}; }break;
你應該格式化你的代碼更好。如果你使用eclipse,你可以點擊ctrl - shift - f來格式化文件。並且您可以在eclipse選項中自定義您的格式化程序。 – 2013-03-24 17:53:20
正如我所說,我一直這樣做了2個月,意味着我不是專業人士,我使用notpad ++。 – minisurma 2013-03-24 18:31:40