Advertisement
Advertisement


Java: Taking String input in console and parsing into Int


Question

Following are the requirements..

Input: The first line of input would consist of a number N, the number of 9*9 matrix. Next N*9 lines would contain the puzzles in the specified format.

Output: A single number which is the sum of all the numbers on the main diagonals of all the given puzzles.

Following is the code I wrote:(Is the logic correct? Why doesit not produce desired output?)

import java.util.Scanner;

class TheInvitationGame{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int a[][][] = new int[n][9][9];
int arr[][] = new int [10][9];

int sum = 0;
String inpline[][] = new String[n][9];

for(int k=0; k<n; k++){
    for(int i=0; i<9; i++){
        inpline[k][i] = sc.next();

        for(int j=0; j<9; j++){
            a[k][i][j] = inpline[k][i].charAt(j);
            if(i==j){
                sum += a[k][i][j];      
            }   
        }
        System.out.println();
    }
}

System.out.println(sum);

}
}

Here, i wish to take 3D array [k][i][j] in which k is use to iterate NO. of 9*9 input matrices, i = line(in String format) that user will enter, j = no. of columns in matrix that will also serve as charAt() variable

Following is the stacktrace:(the 464 output is supposed to be 32(0+2+4+6+8+0+2+4+6)

1 012345678

123456789

234567890

345678901

456789012

567890123

678901234

789012345

890123456

464

2015/01/11
1
4
1/11/2015 6:32:03 PM

Accepted Answer

The problem here is you are putting a char value to a int array resulting the unexpected behaviour.

a[k][i][j] = inpline[k][i].charAt(j);

I'm not sure but I think this will put the ASCII value related to the referring char value to your int array. Which will give you that unexpected answer.
You can fix this by either using the substring() method described in one of the answers and by parsing the resulting string to a int or you can use the Character.getNumericValue(Char ch) method. This method will return the int value for the relevent char variable. So the your code should look like

a[k][i][j] = Character.getNumericValue(inpline[k][i].charAt(j));

This will fix your problem. I tested this and it is providing the desired output.

Please refer to Java API documentation for more details.

2015/01/11
2
1/11/2015 7:14:02 PM

use substring(j,j+1); instead of charAt(j); either you can simply typecast it to int.

2015/01/11

charAt method returns a char value while Integer.parseInt() takes String parameter. You can use substring method as varName[i][k].substring(j,j+1) where j is the index of number.

2015/01/11