[英]I am having troubles reading text into an array, what do I need to change in this code?
This is my current text file that I am trying to read from: 这是我尝试从中读取的当前文本文件:
Buffalo
Montreal
Boston
Ottawa
Toronto
Whenever I run this code, my 5 elements of my array print as "null", so somehow I am not storing the information into the array properly. 每当我运行此代码时,我数组中的5个元素都会显示为“ null”,因此我不知何故没有将信息正确存储到数组中。 Here is the code I have so far!
这是我到目前为止的代码! (I am using the Ready To Program IDE)
(我正在使用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
Thanks for all of your help! 感谢您所有的帮助!
Your for loop has an incorrect condition. 您的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 ();
}
The above should be: i < cities.length;
上面应该是:
i < cities.length;
(i less than cities.length) (我小于city.length)
The loop isn't running, which explains why your array isn't populating. 循环未运行,这说明了为什么未填充阵列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.