Java字符串索引超出范围

0 java for-loop indexof multidimensional-array

所以我得到String索引超出范围意味着我超出了集合的范围,但我不太确定我是如何用我的代码做的.

这段代码应该从一个包含3个整数的文本文件中读取(前两个是分别与行数和列数相关的内容),然后是一系列字符.首先,它读取并保存前三个数字,然后将文件的其余部分转换为String.然后,它通过设置字符数组与文本文件的尺寸,然后在这些值与由字符的文本文件的字符的字符填充遵循此起来.

但是,当我尝试打印出代码时,我遇到字符串索引超出范围错误,无法找到问题.

这是代码:

  import java.util.*;  
  import java.io.*;

public class SnakeBox {
// instance variables
  private char[][] box;
  private int snakeCount;
  private int startRow, startCol;
  private int endRow, endCol;
    private int rows, cols, snakes;
  Scanner keyboard = new Scanner(System.in);

/** Create and initialize a SnakeBox by reading a file.
    @param filename the external name of a plain text file
*/
  public SnakeBox(String fileName) throws IOException{
     Scanner infile = new Scanner(new FileReader(fileName));


     int count = 0;
     String s = "";
     rows = infile.nextInt();
     cols = infile.nextInt();
     snakes = infile.nextInt();
        infile.nextLine();
     box = new char[rows][cols];
     while (infile.hasNext()) {
        s += infile.next();
     }
     for (int i = 0; i < rows; i++) {

        for (int j = 0; j < cols; j++) {
           count++;
           char c = s.charAt(count);           
           box [i][j] = c;
        }
     }
  } 
Run Code Online (Sandbox Code Playgroud)

文本文件是:

    16 21 4
+++++++++++++++++++++
+                   +
+         SSSSS     +
+    S   S          +
+    S    SS        +
+    S      S       +
+ S  S       SS     +
+  SS  S            +
+     S             +
+    S  SSSSSS      +
+   S         S     +
+  S           S    +
+ S     SSS   S     +
+      S     S      +
+       SSSSS       +
+++++++++++++++++++++
Run Code Online (Sandbox Code Playgroud)

谢谢.

gef*_*fei 6

更改

count++;
char c = s.charAt(count);  
Run Code Online (Sandbox Code Playgroud)

char c = s.charAt(count);   
count++;
Run Code Online (Sandbox Code Playgroud)

编辑:另一个问题是Scanner.next()返回下一个标记,忽略所有空格.看到Achintya Jha的答案