数组在for循环之外无法识别

时间:2013-12-09 18:05:16

标签: java arrays string

我正在尝试编写一个程序,从外部文件中获取输入,打印它,然后计算总的世界长度以及文件中3个字母单词的频率。我只应该使用字符串方法...我试图从输入创建一个行数组,然后使用.split创建另一个数组来分析每个单词。但是,每当我尝试测试wordcount或编写一个代码段来计算3个字母单词的频率时,我得到一个无法找到符号的错误...我不知道这意味着什么。有人可以帮我解决错误的含义以及解决方法吗?

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);

}}

引用的外部数据文件读取:

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

2 个答案:

答案 0 :(得分:3)

您正在循环中创建一个局部变量,因此只要您离开循环,它就会超出范围。

阅读变量范围以获取更多详细信息。最简单的解决方法是在进入循环之前声明变量 - 尽管请注意每次都会覆盖变量,因此只有循环的最后一次才能执行任何操作。

你可能真的想这样做:

wordCount += word.length;

内部循环。

答案 1 :(得分:1)

现在,你的代码实际上并没有多大意义。即使在for循环之外可见word[],它也只代表循环完成后的最后一行。

但是,如果您只想更新wordcount而不对代码进行任何重大更改,则可以在循环中更新wordcount

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;
}