这是我当前正在尝试读取的文本文件:
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/