0

I'm getting an input mismatch exception when scanning in data from a text file i created that contains both strings and numbers.

I put a try-catch statement to try and better understand the error, just ignore it.

My driver class:

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

public class BookShelf {

public static void main(String[] args) throws IOException{

    Scanner scan = new Scanner(new File("./src/Books.txt"));
    ArrayList<Books> books = new ArrayList<Books>();

    String author, title, publisher;
    int copyright;
    int count =0;

    try {
    while(scan.hasNext()){
        title = scan.nextLine();
        author = scan.nextLine();
        publisher = scan.nextLine();
        copyright = scan.nextInt();

        Books book = new Books(title,author,publisher,copyright);
        books.add(book);

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


    while (count <books.size() ){
        System.out.println(books.get(count));
        count++;
    }
}
}

My Books constructor class:

public class Books {

private String title, author, publisher;
private int copyright;

public Books(String newTitle, String newAuthor, String newPub, int newCopy ){
title = newTitle;
author = newAuthor;
publisher = newPub;
copyright = newCopy;
}
// Setters
public void setTitle(String newTitle){
    title = newTitle;
}
public void setAuthor(String newAuthor){
    author = newAuthor;
}
public void setPublisher(String newPub){
    publisher = newPub;
}
public void setCopyrightDate(int newCopy){
    copyright = newCopy;
}

// Getters
public String getTitle(){
    return title;
}
public String getAuthor(){
    return author;
}
public String getPublisher(){
    return publisher;
}
public int getCopyrightDate(){
    return copyright;
}
public String toString(){
    String result ="";
    result ="Title: "+title +"\nAuthor: "+author+"\nPublisher: "+ publisher;
    result += "\nCopyright Date: "+copyright;
    return result;
}



}

And my text file:

Java Software Solutions
Lewis & Loftus
Addison-Wesley
2012
Faces in Time
Lewis Aleman
Megalodon Entertainment
2012
Purple Cow
Seth Godin
Portfolio
2002

From the order of my text file and the data types in my while loop I'm having trouble understanding why my code has an input mismatch.

Timmehlkk
  • 41
  • 1
  • 3

0 Answers0