extracting integers from string

R

R

I am reading data from a file, each line has a certain number of
integers. They are seperated by whitespace. When I read them in I use the
readLine() method which reads the lines in as a string. What I am trying to
do is seperate each of these integers so that I can compare them to other
integers on other lines. How do I seperate the integers seeing that they are
all in a single string? This is the code I have tried to use but havent had
any luck as of yet:
String maxVals = in.readLine();
maxVals = maxVals.trim();
System.out.println("Max values are: " + maxVals);
int i = 0;
char buff = maxVals.charAt(i);
System.out.println("buff is: " + buff);
i++;

while (buff.compareTo(' ') > 0){
buff += maxVals.charAt(i);
i++;}

I get an error saying that char cannot be dereferenced. I am not even
sure if this way will work because some of the integers are more than on
digit. When I add them together I won't get a 10 instead I will get 'a'. How
do I extract integers that are more than 1 digit?

Thanks
EF
 
D

dhek bhun kho

I am reading data from a file, each line has a certain number of
integers. They are seperated by whitespace. When I read them in I use the
readLine() method which reads the lines in as a string. What I am trying to
do is seperate each of these integers so that I can compare them to other
integers on other lines. How do I seperate the integers seeing that they are
all in a single string? This is the code I have tried to use but havent had
any luck as of yet:
String maxVals = in.readLine();
maxVals = maxVals.trim();
System.out.println("Max values are: " + maxVals);
int i = 0;
char buff = maxVals.charAt(i);
System.out.println("buff is: " + buff);
i++;

while (buff.compareTo(' ') > 0){
buff += maxVals.charAt(i);
i++;}

I get an error saying that char cannot be dereferenced. I am not even
sure if this way will work because some of the integers are more than on
digit. When I add them together I won't get a 10 instead I will get 'a'. How
do I extract integers that are more than 1 digit?

I would rather use regular expressions to do it, this assumes the integers
are separated by spaces:


String[] parts = in.readLine().split(" ");
for (int i = 0; i < parts.length; i++)
{
try
{
Integer integer = new Integer(parts);
}
catch (NumberFormatException notAnInteger)
{
// do something, log it or whatever.
}
}


greets
bhun
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,902
Latest member
Elena68X5

Latest Threads

Top