Java 如何将包含负数的字符串解析为整数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27372530/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 04:15:02  来源:igfitidea点击:

How to parse string containing negative number into integer?

javaandroidstringparsing

提问by Suroor Ahmmad

Part of my code is here!

我的部分代码在这里!

bufferedReader=new BufferedReader (inputstreamreader);
message=bufferedReader.readLine ();// ex: message has (1,-3)
String[] msg=message.split (",") //I use comma (,) as deliminator
int x=Integer.parseInt (msg [0]);
int y=Integer.parseInt (msg [1]);

This clearly parses but the problem is it looses negative sign. That is the "message" contains (1,-3). Pls help me to parse without loosing -ve sign.

这显然可以解析,但问题是它丢失了负号。即“消息”包含 (1,-3)。请帮助我在不丢失 -ve 符号的情况下进行解析。

采纳答案by Smutje

String message = "1,-3";
String[] msg = message.split(",");
int x = Integer.parseInt(msg[0]);
int y = Integer.parseInt(msg[1]);

System.out.println(x);
System.out.println(y);

Works without a problem. Output:

工作没有问题。输出:

1

-3

1

-3

回答by Karthik Prasad

ParseIntShould work, however you are not getting the result because String[] msg = message.split(",");results in 2 strings with "(1" and other "-10)" try to remove the braces

ParseInt应该可以工作,但是您没有得到结果,因为String[] msg = message.split(",");结果是 2 个带有“(1”和其他“-10)”的字符串尝试删除大括号