user6287161 user6287161 -4 years ago 177
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();
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",")? but it is failing before the first comma.

Thanks in advance!

EDIT: input file for example:

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

Answer Source
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++) { 

Then you can convert the strings to integers.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download