亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Java中解析負數的問題

Java中解析負數的問題

智慧大石 2023-09-06 17:10:10
我有已解析的字符串,我可以拆分所有必要的項目。我可以采用以下值:“|您在一個大的黑暗房間| false 1 -1 -1 2”,“|您在一個黑暗的大房間| false -1 0 -1 -1”,“ |你在一個大房間里,非常暗| false 0 0 3 0 ", "|你在一個暗房間里,非常小| true 0 0 0 0 " 我可以得到描述,真/假值,和數字全部分開。但是,當我嘗試將數字解析為整數值時,出現數字異常錯誤。我最初嘗試使用整數 roomValue 和掃描儀 roomString 將 getNextInt() 放入 roomValue 中。那非常失敗。下面的代碼將所有內容分開,但是一旦我嘗試分配字符串數組的整數值,就會收到錯誤。   description = fullDesc.substring(1, fullDesc.indexOf("| "));        gameRooms[roomNumber] = new Room(description);        fullDesc = fullDesc.substring(fullDesc.indexOf("| ") + 2);        if (fullDesc.contains("true"))             gameRooms[roomNumber].putGrail();        fullDesc = fullDesc.substring(fullDesc.indexOf(" "));               String[] roomString = fullDesc.split(" ");        Integer[] adjRoomNum = new Integer[roomString.length];        for (int i = 0; i < roomString.length; i++) {            //adjRoomNum[i] = Integer.parseInt(roomString[i]);            //System.out.println(adjRoomNum[i]);            System.out.println((roomString[i]));        }        /*        roomValue = roomString.nextInt();        if ((roomValue) >= 0)            gameRooms[roomNumber].setAdjacent(0, gameRooms[Integer.valueOf(roomValue)]);        else if ((roomValue) == -1)            gameRooms[roomNumber].setAdjacent(0, null);        roomString          roomValue = roomString.nextInt();        if ((roomValue) >= 0)            gameRooms[roomNumber].setAdjacent(1, gameRooms[Integer.valueOf(roomValue)]);        else if ((roomValue) == -1)            gameRooms[roomNumber].setAdjacent(1, null);        roomValue = roomString.nextInt();        if ((roomValue) >= 0)            gameRooms[roomNumber].setAdjacent(2, gameRooms[Integer.valueOf(roomValue)]);        else if ((roomValue) == -1)我看到有空格被讀入字符串數組的第一個值,并將解析拋出數字格式異常。我嘗試刪除空白,但沒有成功。
查看完整描述

3 回答

?
偶然的你

TA貢獻1841條經驗 獲得超3個贊

如果您的 roomString 數組包含“1”或“-1”等字符串,那么您可以執行以下部分


for (int i = 0; i < roomString.length; i++) {

  if(roomString[i].charAt(0) == '-'){

    roomString[i] = roomString[i].substring(1);

    adjRoomNum[i] = Integer.parseInt(roomString[i]) * (-1);

  }else{

    adjRoomNum[i] = Integer.parseInt(roomString[i]);

  }

}


查看完整回答
反對 回復 2023-09-06
?
慕村225694

TA貢獻1880條經驗 獲得超4個贊

一旦進行分割,減號和第一個數字之間就有空格 - String[] roomString = fullDesc.split(" "); 第一個字符串是空字符串,因此解析失敗,您應該避免它或刪除它或拆分它


if(fullDesc.startWith("")) {

//substring

}


查看完整回答
反對 回復 2023-09-06
?
繁華開滿天機

TA貢獻1816條經驗 獲得超4個贊

Integer.parseInt?()方法將接受有符號(負)整數值(例如“-1024”)的字符串表示形式,并將該字符串轉換為int。事實上,它也會接受類似“+1024”的內容。它不會轉換的是 Null、Null String ("") 或任何包含一個或多個字母字符(包括空格)的數字字符串。您顯示的錯誤消息表明嘗試通過Integer.parseInt()方法傳遞空字符串 (?""?) 。

恕我直言,在執行轉換之前驗證字符串是一個好主意,這樣可以消除生成異常的擔憂,或者至少嘗試捕獲異常并處理它。

使用String#matches()方法驗證數字字符串:

在此示例中,String#matches()方法與正則表達式(RegEx) 一起使用來驗證roomString[i]數組元素中包含的字符串確實是有符號或無符號整數數值的字符串表示形式。如果不是,則會向控制臺顯示一條錯誤消息,并繼續處理下一個數組元素。

for (int i = 0; i < roomString.length; i++) {

? ? // Trim off an possible leading or trailing whitespaces.

? ? roomString[i] = roomString[i].trim();

? ? if (!roomString[i].matches("\\+?\\d+|\\-?\\d+")) {

? ? ? ? System.err.println("The value " + roomString[i] + " located at " +?

? ? ? ? ? ? ? ? ? ? ? ? ? ?"index " + i + " can not be converted to Integer!");

? ? ? ? continue;? // continue processing the remaining array.

? ? }

? ? adjRoomNum[i] = Integer.parseInt(roomString[i]);

? ? System.out.println(adjRoomNum[i]);

? ? //System.out.println((roomString[i]));

}

使用的正則表達式 ( "\\+?\\d+|\\-?\\d+") 意味著:


\\+?\\d+字符串是否以文字+字符開頭,后跟一個或多個 0 到 9 的數字

|或者

\\-?\\d+"字符串是否以文字-字符開頭,然后后跟 0 到 9 之間的一個或多個數字。

您很可能不需要該部分:\\+?\\d+|并且可以將其從表達式中刪除。


捕獲 NumberFormatException:


for (int i = 0; i < roomString.length; i++) {

? ? // Trim off an possible leading or trailing whitespaces.

? ? roomString[i] = roomString[i].trim();?

? ? try {

? ? ? ? adjRoomNum[i] = Integer.parseInt(roomString[i]);

? ? }

? ? catch (NumberFormatException ex) {

? ? ? ? System.err.println("The value " + roomString[i] + " located at " +?

? ? ? ? ? ? ? ? ? ? ? ? ? ?"index " + i + " can not be converted to Integer!");

? ? ? ? continue;? // continue processing the remaining array.

? ? }


? ? System.out.println(adjRoomNum[i]);

? ? //System.out.println((roomString[i]));

}

您是如何開始獲取空字符串(“”)的?


當解析基于空格的字符串時,特別是如果來自用戶輸入的字符串,總是有可能在某處提供了雙空格,或者在您的情況下是單個前導空格(稍后會詳細介紹)。要處理這種困境,請始終使用String#trim()方法修剪字符串,以在拆分該字符串之前刪除前導和尾隨空格。


解析和分割您的特定字符串:


一般來說,您的解析工作正常,但您會注意到運行此代碼行時:


fullDesc = fullDesc.substring(fullDesc.indexOf(" "));

fullDesc變量將保存帶有前導和尾隨空格的字符串的整數值,例如:" 1 -1 -1 2 "。你不想要這個,因為這會分裂成:"", "1", "-1", "-1", "2"。由于前導空格,您的roomString數組將保存一個 Null String 元素,并且Integer.parseInt()方法不會處理這些元素,因此會拋出NumberFormatException。解決方案很簡單,只需將子字符串索引加1或將trim()方法添加到代碼行末尾即可。將上面的代碼行修改為:


fullDesc = fullDesc.substring(fullDesc.indexOf(" ") + 1);


? ? ? ? ? ? ? ? ? ? ? ? ? O R


// Covers almost all the 'just in case' situations.

fullDesc = fullDesc.substring(fullDesc.indexOf(" ")).trim();?

然而,這并沒有涵蓋當您想要拆分字符串時值之間可能存在雙倍間距的情況,例如:


? ? "1? -1 -1? 2"

這里,我們在 1 和 -1 之間有一個雙倍空格,在 -1 和 2 之間也有一個雙倍空格。當根據單個空格 ( ) 分割該字符串時,String[] roomString = "1? -1 -1? 2".split(" ");您最終將得到六個數組元素,其中兩個為空字符串( "1", "", "-1", "-1", "", "2") ,當遇到 Null String 時, Integer.parseInt()方法最終會拋出 NumberFormatException 。


解決方案是,不要" "在 split 方法中使用。"\\s+"代替使用。這一小正則表達式告訴 split() 方法將字符串拆分為一個或多個空格。


當處理字符串數字時,您想要使用Integer.parseInt()、Double.parseDouble()或任何數字字符串中的空格來解析它們,無論您使用的分隔符如何,都會造成嚴重破壞。以用戶在控制臺應用程序中輸入的逗號 (,) 分隔數字字符串為例:


"1, 2, 3,4,5 ,6 ,7,8 , 9 , 10"

這里有四種不同的分隔情況:


1) 1, 2

2) 3,4

3) 5 ,6

4) , 9 ,

如果你要分割這個字符串,請說:


String[] values = "1, 2, 3,4,5 ,6 ,7,8 , 9 , 10".split(",");

您的值數組將包含:


["1", " 2", " 3", "4", "5 ", "6 ", "7", "8 ", " 9 ", " 10"]

當您嘗試通過Integer.parseInt()方法解析這些元素時,所有包含空格的數組元素都將導致NumberFormatException。為了涵蓋所有基礎,解決方案可能會像這樣拆分:


String[] values = "1, 2, 3,4,5 ,6 ,7,8 , 9 , 10".split("\\s{0,},\\s{0,}");

這個正則表達式是什么意思:"\\s{0,},\\s{0,}"?即使逗號前后有 0 個或多個空格,也會以逗號進行分割。


您的代碼可能如下所示:


String[] gameStrings = {

? ? "|You're in a large dark room| false 1 -1 -1 2 ",

? ? "|You're in a dark large room| false -1 0 -1 -1 ",

? ? "|You're in a large room, very dark| false 0 0 3 0 ",

? ? "|You're in a dark room, very small| true 0 0 0 0 "

};


for (int s = 0; s < gameStrings.length; s++) {

? ? String fullDesc = gameStrings[s];

? ? String description = fullDesc.substring(1, fullDesc.indexOf("| "));

? ? gameRooms[roomNumber] = new Room(description);

? ? fullDesc = fullDesc.substring(fullDesc.indexOf("| ") + 2);


? ? if (fullDesc.contains("true")) {

? ? ? ? gameRooms[roomNumber].putGrail();

? ? }

? ? fullDesc = fullDesc.substring(fullDesc.indexOf(" ")).trim();

? ? String[] roomString = fullDesc.split("\\s+");

? ? Integer[] adjRoomNum = new Integer[roomString.length];


? ? for (int i = 0; i < roomString.length; i++) {

? ? ? ? if (!roomString[i].trim().matches("\\+?\\d+|\\-?\\d+")) {

? ? ? ? ? ? System.err.println("The value " + roomString[i] + " located at "

? ? ? ? ? ? ? ? ? ? + "index " + i + " can not be converted to Integer!");

? ? ? ? ? ? continue; // Continue processing array elements.

? ? ? ? }

? ? ? ? adjRoomNum[i] = Integer.parseInt(roomString[i]);

? ? ? ? System.out.println(adjRoomNum[i]);

? ? }

}


查看完整回答
反對 回復 2023-09-06
  • 3 回答
  • 0 關注
  • 199 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號