簡體   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