Sign in to follow this  

ArrayLists

This topic is 4354 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I have stored a number of Integer objects into a generic ArrayList, and now I want to simply display the list as a string of numbers separated by a comma and a space ", ". I've tried looking at the JavaDocs but they didn't seem to help me.
ArratList<Integer> list = new ArrayList<Integer>();
int x, y, z;
x = 5;
y = 65;
z = 3495;
list.add(x);
list.add(y);
list.add(z);

int i;
String s = "";
for(i = 0; i < list.size(); i++)
{
    s += list.get(i);
    s += ", ";
}


This code throws an IOException.....why!?!?!?

Share this post


Link to post
Share on other sites
Doesn't Java have autoboxing/unboxing now? I also wouldn't expect any of that to throw an IOException. At any rate that code works for me. Are you sure your problem doesn't lie elsewhere?

Enigma

Share this post


Link to post
Share on other sites
Okay here is the real problem:

In order to populate the ArrayList, I make a call to a function, foo(). The foo() function takes a String argument, parses it for numbers, and then creates an ArrayList representing those numbers, returns the list.

In order to parse the passed String, I implement a StreamTokenizer, which for some reason, requires that when the function is declared that it throw an IOException. Ergo my function header:

ArrayList<Integer> foo(String str)
throws IOException

When I compile the source without any calls to foo(), it compiles fine. But the moment I go to use it:

ArrayList<Integer> list = foo("fdjjfh4595kdjrj55");

It dies and reports the following:

unreported exception java.io.IOException; must be caught or declared to be thrown

I'm relatively new to Java, and have never used try/catch blocks before. COuld someone show me how to fix this please?

Share this post


Link to post
Share on other sites
Quote:
Original post by hisDudeness
Okay here is the real problem:

In order to populate the ArrayList, I make a call to a function, foo(). The foo() function takes a String argument, parses it for numbers, and then creates an ArrayList representing those numbers, returns the list.

In order to parse the passed String, I implement a StreamTokenizer, which for some reason, requires that when the function is declared that it throw an IOException. Ergo my function header:

ArrayList<Integer> foo(String str)
throws IOException

When I compile the source without any calls to foo(), it compiles fine. But the moment I go to use it:

ArrayList<Integer> list = foo("fdjjfh4595kdjrj55");

It dies and reports the following:

unreported exception java.io.IOException; must be caught or declared to be thrown

I'm relatively new to Java, and have never used try/catch blocks before. COuld someone show me how to fix this please?

Thats not actually an IOException, it's just the compiler telling you that your code needs to handle the fact that an IOException may occur. Google "checked exceptions". Long story short, either catch the exception (in a try/catch block) and handle it gracefully, or declare that your method throws this exception and catch it further up.

Share this post


Link to post
Share on other sites
Zahlman:


// The purpose of this function is to initialize and ArrayList of
// of integers that represent the questions of a math assignment.

// For example: "3 - 15, 24 - 40 evens, 43 - 57 odd"
// Should produce an ArrayList of:
/*
3,4,5,6,7,8,9,10,11,12,13,14,15,
24,26,28,30,32,34,36,38,40,
43,45,47,49,51,53,55,57
*/

ArrayList<Integer> makeNumberingScheme(String str)
throws IOException
{

// Don't worry about erroneous input for now, such as:
// "20 - 40 odd"

StreamTokenizer st = new StreamTokenizer(new StringReader(str));
st.parseNumbers();

ArrayList<Integer> scheme = new ArrayList<Integer>();
boolean rangeOn = false;
boolean leftRangeOperatorSet = false;
boolean rightRangeOperatorSet = false;
boolean oddsOn = false;
boolean evensOn = false;
int temp = 0;

int token = st.nextToken();

while(token != st.TT_EOF)
{
if(token == st.TT_NUMBER)
{
printError("detected a number");
if(leftRangeOperatorSet) // Left side already set
{
if(rangeOn)
{
// Calculate the new range and add to scheme
if(oddsOn ^ evensOn)
{
if(oddsOn)
{
double x = st.nval;
while(temp != x)
{
scheme.add(new Integer(temp));
temp += 2;
}
}

else // Evens
{
double x = st.nval;
while(temp != x)
{
scheme.add(new Integer(temp));
temp += 2;
}
}
}

else // Neither odds or evens, or both of them
{
double x = st.nval;
while(temp != x)
{
scheme.add(new Integer(temp));
temp++;
}
}
}

else
printError("Two numbers back to back. Invalid input.");
}

else // Beginning of new range
{
leftRangeOperatorSet = true;
double h = st.nval;
temp = (int)h;
}
}

else if(token == st.TT_WORD)
{
printError("detected a word");
String x = st.sval;

x = makeLowercaseString(x);

if(x == "even" || x == "evens")
evensOn = true;
else if(x == "odd" || x == "odds")
oddsOn = true;
else if(x == "-")
rangeOn = true;
else if(x == ",")
{
rangeOn = false;
oddsOn = false;
evensOn = false;
}
}

token = st.nextToken();
}

return scheme;
}



Again, this code compiles, and it doesn't even throw exceptions at me during runtime (hooray). However, it's not reading hyphens ("-") and commas (",") as TT_WORD types, it ignores them completely. And I can't seem to locate the reason why in the JavaDocs.

And so, given the input: "20 - 25", it considers the input as "20 25" and prints the error "Two numbers back to back. Invalid input."

In addition, it doesn't seem to store the numbers into the ArrayList at all.

Share this post


Link to post
Share on other sites
You cannot ignore IO exceptions in Java, as someone already mentioned they are checked exceptions which mean you must have a try/catch block around the code to handle them since by their nature they're more likely to occur than other types of exceptions.

Instead of using IOException try it with plain Exception instead, this isn't checked and your not forced into having a try/catch handler iside your code which should get rid of the error, but if there's a high probability that your code will throw an exception then you should probably leave it as is and write an handler to catch it.

Share this post


Link to post
Share on other sites
Hey,

As long as you are dealing with Java here I may be able to help...

Ignored ',' and '-' Characters
I've had a look at your code and think you're problem may be down to the following line:

st.parseNumbers();

This appears to treat a dash (-) as a negative sign. I don't know exactly what effect this will have on 20 - 25, but it may result in the '-' being ignored as it is without a number. It may be better to process the ',' and '-' yourself.

ArrayList
One question for you regarding your array list. I can't find a reference to the notation you use:

ArrayList<Integer> list = new ArrayList<Integer>();

This looks like a C++ template to me. I tried it using java 1.4.2_08 and 1.5.0_03 and couldn't get it to compile myself, I get the following error:
Syntax error on token "<", invalid AssignmentOperator

AFAIK - The ArrayList type will take any object or combination of objects: it is up to the user to cast the objects on retrieval to the required type. Therefore, you don't need to specify the type stored in the array list on creation. You do need to create an object to store your integer code in, and will need to retrieve it afterwards:


// Create a basic array list
ArrayList list = new ArrayList();

// Add the int using an Integer object
list.add( new Integer(5) );

// Retrieve the array entry, cast to an Integer and get the
// int value it holds.
int myInt = ((Integer)list.get(0)).intValue();



Exceptions

try {
// Some potentially exception causing code here.
// e.g.
int token = st.nextToken();
} catch ( IOException e ) {
// Whatever you want to do if you couldn't do what you tried.
// e.g.
System.error("Couldn't read next token.", e );
} // End try-catch block.



Hope this helps.

Share this post


Link to post
Share on other sites
the <> symbols are a new addition, generics or some such. its valid AFAIK.

it just prevents you having to manually cast when removeing from a collection, and ensuring that only the appropriate types are added. i havent used it yet, but it looks good.

Share this post


Link to post
Share on other sites
Thanks rip-off,

I thought it might be something like that, but wasn't sure. I'll have to look into the latest version of java again by the sounds of it.

If that's the case, I guess my code snippet (sp?) becomes something like:


// Create a basic array list
ArrayList<Integer> list = new ArrayList<Integer>();

// Add the int using an Integer object
list.add( new Integer(5) );

// Retrieve the array entry, cast to an Integer and get the
// int value it holds.
int myInt = list.get(0).intValue();



Which does look a little neater...which is what's important after all.

Share this post


Link to post
Share on other sites
Quote:
Original post by hisDudeness

And so, given the input: "20 - 25", it considers the input as "20 25" and prints the error "Two numbers back to back. Invalid input."


Your string comparisions fail because java.lang.Strings are objects, and == always compares objects for identity (the "-" in your code is not the same "-" as the one just read in from the file, even though they have the "same value") - you need the .equals() method here. Thus the boolean flags never get flipped in the ways that you want.

Share this post


Link to post
Share on other sites

This topic is 4354 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this