这是我目前正在尝试阅读的文本文件:
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
感谢您的所有帮助!
答案 0 :(得分:3)
你的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;
(我小于cities.length)
循环没有运行,这解释了为什么你的数组没有填充。