为了账号安全,请及时绑定邮箱和手机立即绑定

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 关注
  • 86 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信