只在 char 数组中放入一定数量的行

Only put a certain number of lines in a char array

我有一个包含 2939 行的文件,我试图将这五行一起保存在二维字符数组的一个索引中。 所以,

 char [][] myArray;
 myArray[0] = {} //<--char array of first five lines
 myArray[1]= //char array of next five lines

我的实现方式是:

int countLines=0; 
while (sc.hasNext() countLines <5) { //sc is scanner
   //read each line and append to a string builder
   //then convert stringbuilder to char array and
   //store in myArray[0]

   countLines++;
 }

我卡在将接下来的五行存储在 myArray[1] 中。任何帮助,将不胜感激。谢谢!

更喜欢使用列表而不是数组:

    List<String> myArray = new ArrayList<String>();
    while (sc.hasNext()) {
       myArray.add(sc.nextLine());
    }
    // your 5 first line:
    // your 5 first line array:
    List<String> fiveLines = myArray.subList(0, 5);

使用数组列表,因为你不知道数组的大小

 ArrayList<String> strs = new ArrayList<String>();

现在添加为

 strs.add("your string");

获取大小

strs.size();

你可以试试这个

while(sc.hasNext()) {
    if(countLines < 5) {
        //store in myArray[0]
    } else if(countLines >= 5 && countLines < 10) {
        //store in myArray[1]
    }
    countLines++;
 }