wood burning stoves*
The moose likes Beginning Java and the fly likes switch statement Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "switch statement" Watch "switch statement" New topic

switch statement

charlie mills
Ranch Hand

Joined: Nov 01, 2008
Posts: 49
I've created a switch statement and in the second case, i'm getting an error saying that i need to initialised the cities variable. i dont know/understand what to put in case 2 to fix it. cities is the array that i have created from reading data from a text file.
Thanks in advance
case 1:

System.out.println("Cities and temperatures have been read from file");

ArrayList cities = new ArrayList();

Scanner file = new Scanner(new File("CitiesTemps.txt"));

while (file.hasNext())


case 2:

for(int i = 0; i < cities.size(); i++)

fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 10905

Here's your code cleaned up a little. You declare your cities variable inside the 'case 1' block. If your code goes directly into case 2, you've never initialized your variable, since you'd skip line 4. you can declare it outside the case statement entirely.. something like

You still may have problems, though, depending on the structure of the rest of your code.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
charlie mills
Ranch Hand

Joined: Nov 01, 2008
Posts: 49
I tried that and it's working now. thank you
I agree. Here's the link: http://aspose.com/file-tools
subject: switch statement
Similar Threads
help compiling
creating arrays from data in a text file
Scanner question about hasNext() and next()
Implementation of SLR parser