Suroor Ahmmad
Suroor Ahmmad

Reputation: 1162

How to parse string containing negative number into integer?

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.

Upvotes: 3

Views: 51958

Answers (2)

Karthik Prasad
Karthik Prasad

Reputation: 10004

ParseInt Should 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

Upvotes: 0

Smutje
Smutje

Reputation: 18133

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

Upvotes: 6

Related Questions