繁体   English   中英

我在将文本读入数组时遇到麻烦,我需要在此代码中进行哪些更改?

[英]I am having troubles reading text into an array, what do I need to change in this code?

这是我尝试从中读取的当前文本文件:

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; (我小于city.length)

循环未运行,这说明了为什么未填充阵列。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM