-3

I have a set of 3 strings, each in different lines, which are integers separated by spaces.

1 1 2
3 4 4
4 5 5

I wanted to input them into a character array, and I used StringTokenizer in this manner:

for(int j=0;i<n1;i++){
  s2=bure.readLine();         
  st1=new StringTokenizer(s2);

  for(int k=0;k<n2;k++){
    a[j][k]=Integer.parseInt(st1.nextToken());
  }      
}

Where n1 and n2 are the number of rows and columns.

Simulant
  • 19,190
  • 8
  • 63
  • 98
user2277550
  • 553
  • 7
  • 22

2 Answers2

1

You seem to have a typo in your code, first line - that 'i' should be 'j':

for(int j=0;j<n1;j++){
  s2=bure.readLine();         
  st1=new StringTokenizer(s2);

  for(int k=0;k<n2;k++){
    a[j][k]=Integer.parseInt(st1.nextToken());
  }      
}

Try this way. Also using st1.hasMoreElements() seems to be useful in case if you are receiving the data from an external source, and is not built by yourself.

András Iványi
  • 317
  • 1
  • 10
0
    Scanner sc = new Scanner(System.in);
    StringTokenizer st1;
    final int nrLines = 3;
    final int maxNrColumns = 3;
    int[][] a = new int[nrLines][maxNrColumns];
    for (int j = 0; j < nrLines; j++) {
        String s2 = sc.nextLine();
        st1 = new StringTokenizer(s2);
        for (int k = 0; k < maxNrColumns; k++) {
            if (st1.hasMoreElements()) {
                a[j][k] = Integer.parseInt(st1.nextToken());
            }
        }
    }
    // show the array
    for (int i = 0; i < nrLines; i++) {
        for (int j = 0; j < maxNrColumns; j++) {
            System.out.print(a[i][j]);
        }
        System.out.println("");
    }
Michael Besteck
  • 2,415
  • 18
  • 10