2014-01-14 27 views
0

我製作棋盤,只有國王纔會按照國際象棋的規則走棋。 在它的方法下面,它爲King和i的j座標調用了2次,我使用輸入變量String來檢查這個King的座標是否已經存在。比我嘗試將其轉換爲整數,似乎這個轉換有問題。字符串到整數轉換有點問題

import java.util.*; 
public class King { 
    int move(String iK){ 
     Random rand = new Random(); 
     Integer coordinateKing = Integer.valueOf(iK); 
     if (iK == null){   
      coordinateKing = rand.nextInt(8); 
     }else{ 
      int caseI; 
      switch(caseI = rand.nextInt(2)){ 
       case 0: if (coordinateKing < 8){ coordinateKing++; } else {caseI = rand.nextInt(2);} 
       break; 
       case 1: if (coordinateKing > 0){ coordinateKing--; } else {caseI = rand.nextInt(2);} 
       break; 
       default: 
       break; 
      }   
     }  
     return coordinateKing; 
    } 
} 

我的問題是這樣的:

Exception in thread "main" java.lang.NumberFormatException: null 
    at java.lang.Integer.parseInt(Integer.java:454) 
    at java.lang.Integer.valueOf(Integer.java:582) 
    at chess_engine.King.move(King.java:6) 
    at chess_engine.MainClass.main(MainClass.java:12) 

提前感謝!

+1

你能提供'iK'的值嗎? –

+1

'iK'是'null',因此您無法解析它。你可能想要聲明'coordinateKing'並在else塊中移動 'coordinateKing = Integer.valueOf(iK);' –

回答

2

在檢查是否爲null之前,您正試圖將iK轉換爲整數。這條線是拋出異常的地方:

Integer coordinateKing = Integer.valueOf(iK); 

但你檢查if (iK == null)後面的行。你應該先做一個null測試。您可以通過在您的if聲明之前聲明coordinateKing並在if...else塊中設置其值來解決此問題。

Integer coordinateKing = 0; 

if (iK == null){   
    coordinateKing = rand.nextInt(8); 
} else { 
    coordinateKing = Integer.valueOf(iK); 
    int caseI; 
    ... 
} 
+0

謝謝!它現在工作) –

1

這個例外很明顯。 iK是一個空字符串,不能轉換爲整數。當iK爲空時,你想要什麼整數?

2

你叫這個

Integer coordinateKing = Integer.valueOf(iK); 

iK可以爲空在那裏。先進行空檢查

1

這是一個運行時間錯誤:這裏的IK正在接收一個空值和整數對象可以存儲空但該方法valueOf()在內部使用parseInt()方法,它返回一個int值和空的不能被轉換爲int