user6287161 user6287161 - 22 days ago 10
Java Question

Java MisMatchException while using scanner, but why?

Hi I am trying to read an input.txt file by using a scanner, but I keep getting the input mismatch exception and I am unsure why. The file that I am reading in is formatted like this: first is a single number to identify array size. The next line is a list of integers delimited by commas. This is what I have but it fails on the first integer being read in:

File inputFile = new File("input.txt");
Scanner scan = new Scanner(inputFile);
int arraySize = scan.nextInt();
scan.nextLine();
int[] array = new int[arraySize];
for (int i = 0; i < arraySize; i++) {
array[i] = scan.nextInt();
}


I also think I will probably need something in there to catch the commas after each int. Maybe scan.next(",")? but it is failing before the first comma.

Thanks in advance!

EDIT: input file for example:

5
-1, -2, -3 , -4, -5

Answer
File inputFile = new File("C:\\file.txt");
    Scanner scan = new Scanner(inputFile);
    String size = scan.nextLine(); // read size
    String aux = scan.nextLine(); 
    aux = aux.replaceAll("\\s",""); // remove whitespaces for better Integer.parseInt(String)
    String[] parts = aux.split(","); 
    System.out.println("size "+size);
    for (int i = 0; i < parts.length; i++) { 
       System.out.println(parts[i]);
    }
    scan.close();

Then you can convert the strings to integers.

Comments