• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

switch statement

 
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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())
{
cities.add(file.nextLine());
}

break;

case 2:

for(int i = 0; i < cities.size(); i++)
{
System.out.println(cities.get(i));
}

break;
 
lowercase baba
Posts: 13089
67
Chrome Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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.
 
charlie mills
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I tried that and it's working now. thank you
reply
    Bookmark Topic Watch Topic
  • New Topic