NumberFormatException错误(parseInt) [英] NumberFormatException error (parseInt)

查看:167
本文介绍了NumberFormatException错误(parseInt)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

希望这是一个非常简单的查询,但它让我感到头疼。

Hopefully a very simple query, but it's left me scratching my head.

我有一个字符串,这只是一个整数,而我正在尝试然后将该整数作为int获取。面对它应该不是问题。

I have a string, which is just a single integer, and I'm trying to then get that integer out as an int. This on the face of it shouldn't be a problem.

// this is how I create the string (it's the playload from a UDP datagram packet, 
// thought I don't think the origins hugely important - it's juts a test run so the
// stringMessage is always 1 (created by a seperate client process)

  ...
  recvSoc.receive(pac);
  String stringMessage = new String(pac.getData());
  port = pac.getPort();
  System.out.println("RECEIVED: " + stringMessage + " on port:  " + port);
  processMessage(stringMessage);
  ...

// Then in processMessage

public void processMessage(String data) {
  int message;
  message = Integer.parseInt(data);
  ...

这总是因为NumberFormatException错误而崩溃。我不能为我的生活找出导致这种情况的原因,任何想法都会大大增加我没有在Java(最近)编写太多,所以可能只是忘了关键或不合适的事情。

This always crashes with a NumberFormatException error. I cannot for the life of me figure out what's causing this, any ideas greatly appreciated. I haven't coded much in Java (recently) so might simply be forgetting something critical or what not.

Exception in thread "main" java.lang.NumberFormatException: For input string: "1"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:481)
at java.lang.Integer.parseInt(Integer.java:514)
at udp.UDPServer.processMessage(UDPServer.java:85)
at udp.UDPServer.run(UDPServer.java:52)
at udp.UDPServer.main(UDPServer.java:156)


推荐答案

请注意< a href =http://download.oracle.com/javase/6/docs/api/java/net/DatagramPacket.html#getData%28%29 =nofollow> DatagramPackate。 getData() 返回整个缓冲区

您收到的数据只是它:


收到的数据或要发送的数据从偏移开始在缓冲区中,运行 length long。

The data received or the data to be sent starts from the offset in the buffer, and runs for length long.

所以要将数据转换为 String ,你应该使用此构造函数

So to convert the data to a String you should use this constructor:

String message = new String(pac.getData(), pac.getOffset(), pac.getLength(), "UTF-8");

请注意,我在这里指定了UTF-8编码,因为没有指定编码会导致平台要使用的默认编码,通常不是你想要的。

Note that I specify the UTF-8 encoding here, as not specifying an encoding would result in the platform default encoding to be used, which is generally not what you want.

这篇关于NumberFormatException错误(parseInt)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆