gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 18:39:38 24 4
gpt4 key购买 nike

我正在尝试编写一个程序,从外部文件获取输入,打印它,然后计算世界总长度以及文件中 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com