java - for 循环之外无法识别数组

标签 java arrays string

我正在尝试编写一个程序,从外部文件获取输入,打印它,然后计算世界总长度以及文件中 3 个字母单词的频率。我只应该使用字符串方法...我尝试从输入创建一个行数组,然后使用 .split 创建另一个数组来分析每个单词。但是,每次我尝试测试字数或编写代码段来计算 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

最佳答案

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

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

您可能实际上想做:

wordCount += word.length;

在循环内

关于java - for 循环之外无法识别数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20477507/

相关文章:

java - 在 Java 中调用 ResultSet 的 next 时出现超时异常

java - 如何访问受密码保护的网络上的 mp4 视频

c++ - 用分配的最后一个值覆盖数组?

c++ - 具有动态分配大小和预定大小的简单数组内存分配

php - 在php中清理句子

java - 解析字符串时如何获得 Double 而不是 double?

java - 无法使 JAX-WS 绑定(bind)自定义工作

javascript - 使用 javascript 连接两个数组

java - String 是关于 switch 的数字类型并且总是编译为 lookupswitch 吗?

Java - 关于性能和内存使用,为什么最好将字符串使用到静态字段中,而不是每次需要时都声明它?