Combustion007
Combustion007

Reputation: 474

Reading a txt file using scanner class get InputMismatchException. What am I doing wrong?

I am new to Java and following examples from Murach's Java book. I am currently learning how to work with records. I have run into an issue which I cannot seem to resolve. The logic compiles without any issues, however when I try to run the program, I get "INputMismatchException" error on line 23 in "ReadRecords" class. I have googled this issue and searched SOF about this very issue, I did find couple of the solutions, but they didn't help. I would highly appreciate it if someone can help me sort this issue out, please. I have a these classes:

  1. Records Class
  2. ReadRecords Class

Code for Records Class:

class Records{

    public int id;              //ID
    public String name;         //NAME
    public String gender;       //GENDER

}//CLASS

Code for ReadRecords Class:

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

public class ReadRecords {

    //METHOD: MAIN
    public static void main(String[] args){ 

        Scanner input;                              
        final int MAX_LEN = 25;                     
        int counter = 0;                                
        String filePath = "files/records.txt";      

        Records[] rec = new Records[ MAX_LEN ];     
        File file;      

        try {
            file = new File( filePath );
            input = new Scanner( file );

            do{             
                rec[counter].id = input.nextInt();      //INT
                rec[counter].name = input.next();   //STRING
                rec[counter].gender = input.next(); //STRING
                ++counter;
            }
            while(rec[counter -1].id != 0);
        }
        catch ( IOException ex ){       
            System.out.println( "File access error" );  
            counter = 0;
        }//

        System.out.println(rec[0].name);
    }// 
}//

Text file "records.txt"

1, Adam, male
2, Bella, female
3, Charlie, male
4, David, male
5, Elizabeth, female
6, Frank, male
7, Ginger, female
8, Harry, male
9, Irene, female
10, Jill, female

Thank you.

enter image description here

Upvotes: 0

Views: 238

Answers (3)

JNeether
JNeether

Reputation: 25

I would honestly use a different method of accessing the text file. Google FileReader as well as BufferedReader, they are the file accessors I was told to use in my intro classes. I will post below the code I came up with to get the Records objects created from the text file. It is by no means the best way to do it, but it does get the job done. Feel free to ask questions about the code I used that may be unfamiliar.

    import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;


class Records {

    public int id;              //ID
    public String name;         //NAME
    public String gender;       //GENDER

}


public class ReadRecords {

    public static void main(String[] args) {

        String filePath = "records.txt";      

        ArrayList<Records> rec = new ArrayList<Records>();           

        try {
            FileReader fr = new FileReader(filePath);
            BufferedReader br = new BufferedReader(fr);
            String nextLine;
            String splitText[];

            while((nextLine = br.readLine())!= null){
                Records temp = new Records();
                splitText = nextLine.split(", ");
                temp.id = Integer.parseInt(splitText[0]);
                temp.name = splitText[1];
                temp.gender = splitText[2];
                rec.add(temp);

            }
            br.close();
        }
        catch ( IOException ex ){       
            System.out.println( "File access error" );  
        }//

        for (int i = 0; i < rec.size(); i++) {
            System.out.println("Record ID: " + rec.get(i).id 
                    + "\n" + "Record Name: " + rec.get(i).name + "\n" + "Record Gender: " + rec.get(i).gender);
        }
    }// 

}

On a side note, I would suggest downloading an IDE such as Eclipse for ease of use.

Upvotes: 0

gowtham
gowtham

Reputation: 987

The input you are searching is int, but you have string in first place so you are getting inputMismatchException as the default delimter of scanner is space,

In your text file you have ", " as delimiter.so use that

input = new Scanner( file ).useDelimiter(", ");

And secondly rec[counter].id throws NullPointerException as you initially will have null values in the array. so change that as shown below

do{        
                Records record=new Records();
                record.id = input.nextInt();      //INT
                record.name = input.next();   //STRING
                record.gender = input.next(); //STRING
                rec[counter]=record;
                ++counter;
            }
            while(input.nextLine() != null);

Upvotes: 2

Ashishkumar Singh
Ashishkumar Singh

Reputation: 3600

Default delimter of scanner is space, but in your text file you have data seperated by space as well as new line charater. So you need to use delimiter as ', ' as well as '\n\r'.

Also you can change your wile condition to

while (input.hasNext() && (input.next() != null));

Here is the modified code of your's which ran for me. To simply the things, I removed all the commas in your txt file and used the following pattern as delimter - [ \r\n]. And it ran succesfully.

import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import java.util.regex.Pattern;

class Records
{

    public int id; // ID
    public String name; // NAME
    public String gender; // GENDER

}// CLASS

public class ReadRecords
{

    // METHOD: MAIN
    public static void main(final String[] args)
    {

        Scanner input = null;
        final int MAX_LEN = 25;
        int counter = 0;
        final String filePath = "records.txt";

        final Records[] rec = new Records[MAX_LEN];
        File file;

        try
        {
            file = new File(filePath);
            input = new Scanner(file);
            final Pattern pat = Pattern.compile("[ \r\n]");
            input.useDelimiter(pat);
            do
            {
                rec[counter] = new Records();
                rec[counter].id = input.nextInt(); // INT
                rec[counter].name = input.next(); // STRING
                rec[counter].gender = input.next(); // STRING
                ++counter;

            }
            while (input.hasNext() && (input.next() != null));
        }
        catch (final IOException ex)
        {
            System.out.println("File access error");
            counter = 0;
        }//

        System.out.println(rec[0].name);
    }//
}//

Upvotes: 1

Related Questions