java - 我在将文本读入数组时遇到问题,我需要在此代码中更改什么?

标签 java arrays

这是我当前正在尝试读取的文本文件:

Buffalo
Montreal
Boston
Ottawa
Toronto

每当我运行此代码时,数组的 5 个元素都会打印为“null”,因此不知何故我没有将信息正确存储到数组中。这是我到目前为止的代码! (我正在使用 Ready To Program IDE)

// The "Hockey" class.
import java.awt.*;
import hsa.Console;
import java.io.*;

public class Hockey
{
    static Console c;           // The output console

    public static void main (String[] args) throws IOException
    {
        c = new Console ();

        //setting up file reading
        FileReader fr = new FileReader ("cities.txt");
        BufferedReader br = new BufferedReader (fr);

        //initialising array
        String cities[] = new String [5];

        //loop to read in the 5 entries
        for (int i = 0 ; i > cities.length ; i++)
        {
            cities [i] = br.readLine ();
        }

        //loop to print all elements of "cities" to the console
        for (int i = 0 ; i < cities.length ; i++)
        {
            c.println (cities [i]);
        }
            // Place your program here.  'c' is the output console
    } // main method

} // Hockey class

感谢您的帮助!

最佳答案

您的 for 循环条件不正确。

//loop to read in the 5 entries
for (int i = 0 ; i > cities.length ; i++) //reads as (i greater than cities.length)
{                ^^^^^^^^^^^^^^^^^
    cities [i] = br.readLine ();
}

上面应该是:i < cities.length; (i 小于城市.长度)

循环没有运行,这解释了为什么你的数组没有填充。

关于java - 我在将文本读入数组时遇到问题,我需要在此代码中更改什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29857408/

相关文章:

c - 为什么这个c程序会崩溃?

java - 如何在java中使用for循环减去n个数字?

java - 循环导致数组旋转超时

python |如何从二维数组中删除子数组

java - HttpSessionListener 是否一直有效?

mysql - Laravel 过滤多个WhereIn 数组

c# - 将数组从 vba 传递到 c# 时,数据类型不匹配在哪里?

java - 无法在另一个类中创建打印方法并在主类中调用它

java - 如何使用 Java 泛型将 "T"参数作为方法参数传递?

java - 如何从 SWT 与 Javascript 函数对话