for loop - Java string index out of range -


so string index out of range means i'm exceeding range of collection, i'm not quite sure how i'm doing code.

this code supposed read text file contains 3 ints( first 2 being relevant number of rows , number of columns respectively) , series of characters. first reads , saves first 3 numbers, converts rest of file string. follows setting array of chars dimensions of text file , filling in values characters of text file character character.

however, when try print out code, encounter string index out of range error , cannot find problem.

this code:

  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 , initialize snakebox reading file.     @param filename external name of 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();      }      (int = 0; < rows; i++) {          (int j = 0; j < cols; j++) {            count++;            char c = s.charat(count);                       box [i][j] = c;         }      }   }  

the text file :

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

thank you.

the problem not stated above: in given file there 59 tokens equals 117 characters total (i counted manually) . whereas maximum value of count reach 21*16 =336.

if input file named "infile.dat" has following format:

hello there 1234
csstudents goodbye 6556

it has 6 tokens can read in using following code:

while (filein.hasnext()) {      // while there token read     string s = filein.next();   // reads in string tokens "hello" "csstudents"      string r = filein.next();   // reads in string tokens "there" "goodbye"     int x = filein.nextint();   // reads in int tokens 1234  6556   } 

notice how scanner object skips on white-space characters start of next token. suggestion use scanner#hasnextline() & scanner#nextline()

while (infile.hasnextline) {     s += infile.nextline(); } 

Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -