开发者

scanner class and skipping patterns

I want to be able to read a text file for its rows and columns and put the data in a matrix. this is what i got so far. i have a matrix class with one data member called element of type int and it's a 2-d array [][].

import java.io.*;
import java.util.*;

public class test{
    public sta开发者_如何转开发tic void main(String args[]) throws FileNotFoundException {
    File fin = new File ("matrix1.txt");
    Scanner scanner = new Scanner(fin);
    scanner.next(); // removes the first line in the input file 
    int rows = scanner.nextInt();
    int cols = scanner.nextInt();
    while (scanner.hasNextLine()){
         String line = scanner.nextLine();
         System.out.println(line);
         }
    System.out.println(rows);
    System.out.println("/n");
    System.out.println(cols);
    }

}

The sample text file is as follows. I want to take the rows and columns so i can dynamically declare the matrix and then store its values. i get the error saying INPUTMISMATCH exception. help would be appreciated.

<matrix>
    rows = 2
    cols = 2

1 2
2 4 
</matrix>


From the javacdocs, an InputMismatchException is thrown "if the next token does not match the Integer regular expression, or is out of range".

You're trying to scan a string "row = 2" as an integer. You can't use nextInt in this case. Try nextLine and then split on = to get the value.

Example:

String rowLine = scanner.nextLine();
String[] arr = rowLine.split("=");
int rows = Integer.parseInt(arr[1].trim());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜