简体   繁体   English

java.lang.NumberFormatException:对于输入字符串:“5

[英]java.lang.NumberFormatException: For input string: "5

When I run this Java code: 当我运行这个Java代码时:

public void run(){
    String stringPacketData=null;
    try {
        stringPacketData = new String(clientPacketData,"UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        System.exit(1);
    }       
    String[] splitString=stringPacketData.split("@");
    this.clientID = Integer.parseInt(splitString[0]);
    String op="";

    op=splitString[1];
    if(op.equalsIgnoreCase("popola_cache")){
        popolamentoCache(Integer.parseInt(splitString[2]));
    }
    else{
        System.exit(0);
    }
} 

Where stringPacketData has a format: idClient@operationType@dimCache, it will throw this excpetion: 其中stringPacketData的格式为:idClient @ operationType @dimCache,它将抛出此excpetion:

Exception in thread "Thread-2" java.lang.NumberFormatException: For input string: "5"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at UDPSocketBased.WorkerUDP.run(WorkerUDP.java:53)

WorkerUDP.java:53 statement corresponds to: popolamentoCache(Integer.parseInt(splitString[2])); WorkerUDP.java:53语句对应于:popolamentoCache(Integer.parseInt(splitString [2]));

I can't understand why my input string "5" is not in the correct format. 我无法理解为什么输入字符串“5”的格式不正确。

首先,您需要在尝试解析之前修剪字符串

this.clientID = Integer.parseInt(splitString[0].trim());

I resolve it in this way: 我以这种方式解决它:

popolamentoCache(Integer.parseInt(String.valueOf(splitString[2].charAt(0))));

The problem was that I received a DatagramPacket called "pkt": 问题是我收到了一个名为“pkt”的DatagramPacket:

byte[] buffer=new byte[65508];
DatagramPacket pkt = new DatagramPacket(buffer, buffer.length);

So, when I get my packet data with: 所以,当我得到我的包数据时:

clientPacketData=pkt.getData();

it considers a payload length of 65508 byte, in the same way stringPacketData length. 它认为有效载荷长度为65508字节,与stringPacketData长度相同。

Thanks! 谢谢!

Try put one delimiter character, the same that you use to split the string at the beginning of yours text file. 尝试放置一个分隔符,与您在文本文件开头分割字符串时使用的字符相同。 This way you avoid the situation when first character throws the exception because that's not a integer. 这样就可以避免第一个字符抛出异常时的情况,因为它不是整数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM