user2817797
user2817797

Reputation: 7

arrays not recognized outside of for loop

I am trying to write a program that takes input from an external file, prints it, then calculates total world length and also the frequency of 3 letter words within the file. I'm only supposed to use string methods... I have tried to create an array of lines from the input and then create another array using .split to analyze each word. However, everytime I try to test wordcount or write a code segment to calculate frequency of 3 letter words, I get an error of can not find symbol... I don't know what this means. Can someone help me with what the error means and how to fix it, please?

import java.util.*;
import java.io.*;

public class Program
{
public static void main(String args[]) 
{

Scanner inFile = null; //adds the data
try { 
inFile = new Scanner (new File("prog512h.dat"));} 
catch (FileNotFoundException e) {
System.out.println ("File not found!");
System.exit (0);}      

    String[] line = new String[18]; //there are 18 lines of code in the external file
    int wordcount=0;


    for (int i=0; i<18; i++){
    line[i] = inFile.nextLine();
    System.out.println(line[i]);
    String word[] = line[i].split(" ");  
    }

    wordcount = word.length();
    System.out.println();
    System.out.println("Total Wordcount: " +wordcount);

}}

The external data file referenced reads this:

Good morning life and all
Things glad and beautiful
My pockets nothing hold
But he that owns the gold
The sun is my great friend
His spending has no end
Hail to the morning sky
Which bright clouds measure high
Hail to you birds whose throats
Would number leaves by notes
Hail to you shady bowers
And you green fields of flowers
Hail to you women fair
That make a show so rare
In cloth as white as milk
Be it calico or silk
Good morning life and all
Things glad and beautiful

Upvotes: 0

Views: 287

Answers (2)

Right now, your code as it is, doesn't make very much sense. Even if word[] was visible outside your for loop, it would only represent the very last line after the loop was done.

But, if you just want to update the wordcount without making any major changes to your code, you can update wordcount inside your loop

int wordcount = 0;

for (int i=0; i<18; i++)
{
    line[i] = inFile.nextLine();
    System.out.println(line[i]);
    String word[] = line[i].split(" ");  
    wordcount += word.length;
}

Upvotes: 1

Tim B
Tim B

Reputation: 41178

You are creating a local variable inside a loop, so as soon as you leave the loop it goes out of scope.

Read up on variable scoping for more detail. The easiest fix is to declare the variable before you enter the loop - although note that that would overwrite the variable each time so only the last time around the loop would do anything.

You probably actually want to do:

wordCount += word.length;

Inside the loop.

Upvotes: 3

Related Questions