2014-02-17 50 views
2

我在運行以下代碼並輸入5x5的大小時出現此錯誤。不知道爲什麼?NumberFormatException的Java錯誤

當我輸入10x10它似乎運行良好,但我不知道輸出是否正確。

Exception in thread "main" java.lang.NumberFormatException: For input string: "" 
    at java.lang.NumberFormatException.forInputString(Unknown Source) 
    at java.lang.Integer.parseInt(Unknown Source) 
    at java.lang.Integer.parseInt(Unknown Source)" 

這裏是我的代碼

import java.util.Scanner; 

    public class CheckerBoard { 

     public static void main(String [] args){ 

     Scanner userInput = new Scanner(System.in); 

     System.out.println("What two colors would you like your board to be?"); 

     String colorOne = userInput.next(); 
     String colorTwo = userInput.next(); 

     do {  
      System.out.println("How big should the checker board be? (Square sizes only please)" + "\n" 
       + "Please enter it like 4x4 with whatever numbers you choose."); 

      String boardSize = userInput.next(); 

      int intOne = Integer.parseInt(boardSize.substring(0,boardSize.indexOf("x"))); 
      System.out.println(boardSize.indexOf("x")); 
      int intTwo = Integer.parseInt(boardSize.substring(boardSize.indexOf("x")+1, boardSize.length()-1)); 
      System.out.println(intOne); 

     } while(false); 
     } 
    } 

    //keep in mind that this program is not done yet, this is just a current issue I am having atm. 
+0

如果您可以指定異常來自的行,這將有所幫助。對我來說,你似乎至少在一個子串方法調用中使用了錯誤的索引。 –

回答

1

的問題是在這裏:

int intTwo = Integer.parseInt(boardSize.substring(boardSize.indexOf("x")+1, boardSize.length()-1)); 

你走的是從子到xlength - 1。您應該從xlength,因爲substring不包含第二個索引。

因此,您在5x5上收到錯誤,因爲x後只有一個字符。所以你試圖給parseInt一個空字符串。您在10x10上沒有例外,但您只使用10x1

因此,你應該改變行這樣的:

int intTwo = Integer.parseInt(boardSize.substring(boardSize.indexOf("x")+1, boardSize.length())); 
0

您的代碼不會考慮到這條線時,boardSize串實際上可能是空的;

int intOne = Integer.parseInt(boardSize.substring(0,boardSize.indexOf("x"))); 

當你做「indexOf」,搜索不存在的東西 - 你會得到-1回來,這是作爲你的子字符串的參數無效。

0

你試過嗎?

 int intTwo = Integer.parseInt(boardSize.substring(boardSize.indexOf("x")+1, boardSize.length())); 

可能你看的時間越長就會解決解析問題。

2

我相信一個更安全的方式來做到這將是拆就x

String boardSize = userInput.next(); 
String[] split = boardSize.split("x"); 
int intOne = Integer.parseInt(split[0]); 
int intTwo = Integer.parseInt(split[1]); 

顯然消毒的有害輸入!

0

變化
int intTwo = Integer.parseInt(boardSize.substring(boardSize.indexOf("x")+1, boardSize.length()-1));

int intTwo = Integer.parseInt(boardSize.substring(boardSize.indexOf("x")+1, boardSize.length()));
記住,傳遞給String.substring第二索引將不會被包含在返回值。