1

so i have to read a matrix from .txt file, which is of the format given below.

problemMatrix = [[101, 2, 3, 4, 5, 6, 7, 8, 9, 10], [11, 12, 13, 14, 15, 16, 17, 18, 19, 20], [21, 22, 23, 24, 25, 26, 27, 28, 29, 30], [31, 32, 33, 34, 35, 36, 37, 38, 9, 40], [41, 42, 43, 44, 45, 46, 47, 28, 49, 50], [51, 52, 53, 54, 55, 56, 57, 58, 59, 60], [61, 62, 63, 64, 65, 66, 67, 68, 69, 70], [71, 72, 73, 7, 75, 76, 77, 78, 79, 80], [81, 82, 83, 84, 85, 86, 87, 88, 89, 90], [91, 92, 93, 94, 95, 96, 97, 98, 99, 100]]

i have already written code to calculate the rows and columns. I have written this code to get the integer value in [i][j] index.

    int [][] input= new int[rows][cols]; 
    matrix = new Scanner(new File("test.txt"));
    matrix.useDelimiter("[ ,\r\n\t=]");
    try{    
        for(int i=0; i<rows; i++){
            for(int j = 0;j<cols;j++){
                input[i][j]=matrix.nextInt();
                System.out.print(input[i][j] + " ");
            }
            System.out.println();

            }   
    }
    catch(InputMismatchException e){
        System.out.println(e);
    }

but this is giving me exception InputMismatchException. Any suggestions. I don't understand how to change the delimiters for scanner. Thanks.

roeygol
  • 4,908
  • 9
  • 51
  • 88
  • share content of text.txt – SarthAk Oct 02 '16 at 05:56
  • Does "problemMatrix = " exist in your txt file? If yes, then it doesn't match the regex that you provided, hence the exception. Try reading this https://docs.oracle.com/javase/7/docs/api/java/util/InputMismatchException.html – Nishit Oct 02 '16 at 06:11
  • yes, the matrix i have given above is taken from the test.txt and it contains problem matrix – Chintan Patel Oct 02 '16 at 22:07

1 Answers1

0

I think the problem is with your regex. The regex [ ,\r\n\t=] means "match any of , \r, \n, \t or =. Note that it will NOT match [ or ].

You should include both [ and ] inside your square brackets, and make sure that they're escaped, and that should help. You may also have an issue with multiple delimeters leading to your scanner trying to parse an empty string, so you will want your regex to match multiple of these characters together.

Joe C
  • 15,324
  • 8
  • 38
  • 50