ArrayLists

Started by
12 comments, last by Zahlman 18 years, 3 months ago
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!?!?!?
Well I believe in God, and the only thing that scares me is Keyser Soze.
Advertisement
list.add( new Integer(x) ); maybe?

dont know about the IOException, but other than that your code looks okay
yeah rip-off is right.

look here: ArrayList list = new ArrayList<Integer>
the Integer is a class not the POD int. you need to add Integer objects to the list not regular ints.

Beginner in Game Development?  Read here. And read here.

 

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
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?
Well I believe in God, and the only thing that scares me is Keyser Soze.
Show your StreamTokenizer implementation.
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.
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.
Well I believe in God, and the only thing that scares me is Keyser Soze.
Still having problems with this one guys.....anyone?
Well I believe in God, and the only thing that scares me is Keyser Soze.
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.

This topic is closed to new replies.

Advertisement