2013-04-05 151 views
0

因此,我得到的字符串索引超出范围意味着我超出了集合的范围,但我不太确定我是如何使用我的代码执行此操作的。Java字符串索引超出范围

该代码应该从包含3个整数的文本文件(前两个分别与行数和列数相关)以及一系列字符中读取。所以首先读取并保存前三个数字,然后将文件的其余部分转换为字符串。然后,通过设置一个带有文本文件尺寸的字符数组,然后用字符逐个字符地填充文本文件的字符来填充这些值。

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

这是代码:

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; 
     } 
    } 
    } 

的文本文件是:

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  + 
+++++++++++++++++++++ 

谢谢。

回答

2

问题并非如上所述: 在给定的文件中,有将近59个令牌将等于总共117个字符(我手动计算)。计数的最大值将达到21 * 16 = 336。

如果名为“infile.dat”输入文件的格式如下:

你好1234个
CSstudents再见6556

它有6个令牌,我们可以使用下面的代码阅读:

while (filein.hasNext()) {  // while there is another token to read 
    String s = filein.next(); // reads in the String tokens "Hello" "CSstudents" 
    String r = filein.next(); // reads in the String tokens "There" "goodbye" 
    int x = filein.nextInt(); // reads in the int tokens 1234 6556 

} 

请注意扫描仪对象如何跳过所有空格字符到下一个标记的开始位置。 所以我的建议是使用Scanner#hasNextLine() & Scanner#nextLine()

while (infile.hasNextLine) { 
    s += infile.nextLine(); 
} 
+0

检查文档http://docs.oracle.com/javase/1.5.0/docs/ api/java/util/Scanner.html#next%28% 就像Achintya所说的next()返回一个标记。文件中的所有空白都会被忽略。 – Alex 2013-04-05 09:27:22

+0

嗯谢谢你,这是一个大问题,我怎么能够保存我阵列中的空白空间呢? – user2248256 2013-04-05 09:27:53

+0

+1。我没有看到这 – gefei 2013-04-05 09:31:17

6

变化

count++; 
char c = s.charAt(count); 

char c = s.charAt(count); 
count++; 

编辑:另一个问题是,Scanner.next()返回一个令牌,忽略所有的空间。请参阅Achintya Jha的回答

+1

事实上,当你在最后一个索引,这将导致一个问题。假设你在索引10(这是最后一个),你将尝试获取不存在的charAt()索引11。大发现 – 2013-04-05 09:07:23

+0

啊,谢谢你,愚蠢的错误。但是,再次运行该文件仍然会在同一位置出现字符串索引超出范围异常。 – user2248256 2013-04-05 09:09:19

+0

@ user2248256 hmm。我会尝试打印s的值,它的长度,然后显示count的值以查看最新情况 – gefei 2013-04-05 09:11:44

相关问题