Help with Java String to Int Conversion

Status
Not open for further replies.
Can someone please let me know why this is throwing a runtime exception? What's the best way to go from a String to an Integer?

Thanks


//AdditionServer.java
import java.net.*;
import java.io.*;
import java.util.*;

public class AdditionServer{
public static void main(String args[]) throws IOException{
int port=4450;
ServerSocket server=new ServerSocket(port);
while(true){
System.out.println("Waiting for client...");
Socket client=server.accept();
InputStream in=client.getInputStream();
byte a[]=new byte[100];
int num=in.read(a);
String data=new String(a);
System.out.println("Server received:" + data);

int number;
number=Integer.parseInt(data);
System.out.println("Integer " + number);
}
}
}
 

m1sh1

Smack-Fu Master, in training
89
rgrizzzz wrote:
<BLOCKQUOTE>code:<HR>
Code:
int number;
number=Integer.parseInt(data);
System.out.println("Integer " + number);
<HR></BLOCKQUOTE>

Why bother with the Integer.parseInt(data) statement. I mean essentially the println statment when doing ("Integer " + number) will convert number into a string. So if you have no other use for number in your program then you might as well just print out data.

Also make sure that data is a valid number string, i.e. all the chars in data string are numerals and the first char can be a '+' or '-' otherwise as stated above NumberFormatException is thrown which is a RuntimeException
 
Make sure that your conversion to a string to calculate the integer from doesn't add any extraneous characters anywere. You have.
code:<HR>
Code:
byte a[]=new byte[100];
int num=in.read(a);
String data=new String(a);

Which should, if I'm not mistaken, make a 100 character long string. When you do your first print of the data to see if it is correct, try something like:
code:<HR>
Code:
System.out.println(data+"X");

That way you can make sure that there are no extraneous characters on the end between the end of the number and the "X".

gen
 
I know that I'm not getting any extra characters. What I'm trying to do is to take in data from the client. The data is going to be any integer. I need to get the data back to the form of an integer on the server side so I can do some calculations with it and send the results of the calculations back to the client.

Does anyone know what's generating the Number Format Exception or a way to get around this?

Thanks
 
Ok, the conversion process was ok all the along. The problem is that it doesn't like the fact that it's trying to change the blank areas in the array to an integer. The first value in the array is an string. If I change the length of the array to one everything works fine, except when I enter an integer bigger than 9. Anyone know how to fix this? I can't seem to get the read method to work with anything other than a byte.

This is pissing me off.
 
Status
Not open for further replies.