Beginer with Java need help

Status
Not open for further replies.

krtola

Ars Scholae Palatinae
1,205
Hello guys.

I have this string in my program, and i want to parse the last number in the string so i can use it do calculate time. Here is how the string looks like:

"Client Transmited Word: Sarajevo BiH Client Send Time in ms: 1272838801913"

What i use now is this to parse out the number is:

Code:
String input = is.readLine();
             //obtain received time on server
             long ServerReceiveTime = System.currentTimeMillis();
             long ClientSendTime = nm.parseLong(input, 55);

Note: nm is object defined as Long

But it just keeps throwing exception. What am i doing wrong?

Thanks
 

Wind

Wise, Aged Ars Veteran
155
walkitiki":1snz8jyp said:
If you are continually doing this, you could use the Scanner class. Import it from java.util.Scanner. The constructor just uses the input stream as a parameter and there are lot of useful functions that might be handy if you're doing a lot of parsing. For example:

Code:
Scanner parser = new Scanner(System.in)
long time = parser.nextLong();
That's not quite how it works. When you call nextLong() and give it string it won't be happy, you still have to give it a long and only a long. The reason it worked in the javadoc example is because they used delimiters.

As for the OP "nm.parseLong(input, 55)" will try to convert the string you just read in from base 55 to base 10, which is why you are getting a NumberFormatException. In this case I would use:

Code:
int lastSpace = line.lastIndexOf(" ")+1;
line=line.substring(lastSpace,line.length());
long time = Long.parseLong(line);

lastIndexOf is inclusive so it will include the space it found which is why you need to add 1. You then take the substring from beginning of long to the end of the string. This assumes that the long will always be last in the string. I'd also suggest learning regular expressions they are amazing when it comes to parsing.
 
Status
Not open for further replies.