NoSuchElementException ocurring inside the code - java

Here , I have used two classes to combine the concept of Serialization & Deserialization and Collections.
When I run the program , i get a runtime exception "NoSuchElementException".
I have used the Employee class to store the basic info of an Employee.
The class DemoEmployee is the main class in which four methods are declared.
To add an employee's info (it's object to the Linked List object I created).
To display the info of all the Employee class objects present in the Linked List object.
To serialize the Linked List object
To deserialize the Linked List object
How to resolve this issue?
import java.io.Serializable;
public class Employee_6033 implements Serializable {
private int empid_6033;
private String empname_6033;
private String empdes_6033;
private int empsalary_6033;
public Employee_6033(int empid_6033, String empname_6033, String empdes_6033, int empsalary_6033) {
// TODO Auto-generated constructor stub
this.empid_6033 = empid_6033;
this.empname_6033 = empname_6033;
this.empdes_6033 = empdes_6033;
this.empsalary_6033 = empsalary_6033;
}
int getEmpId_6033() {
return empid_6033;
}
String getEmpName_6033() {
return empname_6033;
}
String getEmpDes_6033() {
return empdes_6033;
}
int getEmpSalary_6033() {
return empsalary_6033;
}
}
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class DemoEmployee_6033 {
static List<Employee_6033> l_6033 = new LinkedList<Employee_6033>();
int n_6033;
int i_3033;
void addEmployee_6033() {
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of employees : ");
n_6033 = input.nextInt();
for (i_3033 = 1; i_3033 <= n_6033; i_3033++) {
System.out.println("\nEnter Employee " + i_3033 + "'s Details :");
System.out.print("\tEnter ID : ");
int id_6033 = input.nextInt();
input.nextLine();
System.out.print("\tEnter Name : ");
String name_6033 = input.nextLine();
System.out.print("\tEnter Designation : ");
String des_6033 = input.nextLine();
System.out.print("\tEnter Salary : ");
int salary_6033 = input.nextInt();
l_6033.add(new Employee_6033(id_6033, name_6033, des_6033, salary_6033));
}
input.close();
}
void display_6033() {
int j_6033 = 1;
for (Employee_6033 ref_6033 : l_6033) {
System.out.println("Employee " + j_6033);
System.out.println("\tID : " + ref_6033.getEmpId_6033());
System.out.println("\tName : " + ref_6033.getEmpName_6033());
System.out.println("\tDesignation : " + ref_6033.getEmpDes_6033());
System.out.println("\tSalary : " + ref_6033.getEmpSalary_6033());
j_6033++;
}
}
void serialize_6033() {
try {
String filename_6033 = "";
Scanner input = new Scanner(System.in);
System.out.print("Enter the name of the file you want to Read from : ");
filename_6033 = input.nextLine();
// Saving of object in a file
FileOutputStream file_6033 = new FileOutputStream(filename_6033);
ObjectOutputStream out_6033 = new ObjectOutputStream(file_6033);
// Method for serialization of object
out_6033.writeObject(l_6033);
out_6033.close();
file_6033.close();
System.out.println("Object has been serialized");
input.close();
}
catch (IOException ex) {
System.out.println("IOException is caught");
}
}
void deserialize_6033() {
l_6033 = null;
try {
String filename_6033;
Scanner input = new Scanner(System.in);
System.out.print("Enter the name of the file you want to Write to : ");
filename_6033 = input.nextLine();
// Reading the object from a file
FileInputStream file_6033 = new FileInputStream(filename_6033);
ObjectInputStream in_6033 = new ObjectInputStream(file_6033);
// Method for deserialization of object
l_6033 = (List<Employee_6033>) in_6033.readObject();
in_6033.close();
file_6033.close();
System.out.println("Object has been deserialized ");
display_6033();
input.close();
}
catch (IOException ex) {
System.out.println("IOException is caught");
}
catch (ClassNotFoundException ex) {
System.out.println("ClassNotFoundException is caught");
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
DemoEmployee_6033 de_6033 = new DemoEmployee_6033();
int choice_6033;
do {
System.out.println("\n********* MENU *********");
System.out.println("--------------------------");
System.out.println("1. Add Employee");
System.out.println("2. Display Employee Details");
System.out.println("3. Write Data into a File - Serialization");
System.out.println("4. Read Data from a File - Deserialization");
System.out.println("5. Exit");
System.out.println("--------------------------");
System.out.print("Enter you Choice : ");
choice_6033 = input.nextInt(); //Error comes here after 1 iteration.
switch (choice_6033) {
case 1:
de_6033.addEmployee_6033();
break;
case 2:
de_6033.display_6033();
break;
case 3:
de_6033.serialize_6033();
break;
case 4:
de_6033.deserialize_6033();
break;
case 5:
break;
default:
System.out.println("You have entered an invalid choice!");
break;
}
} while (choice_6033 != 5);
input.close();
}
}

NoSuchElementException is thrown, because you call input.close() extensively, where in your case it should be called only once. I have removed input.close(); occurrences (except main method) and your code worked fine.
There reason for this that calling Scanner.close() will in fact close whole System.in and every future related method calls, like input.nextInt() in your case, will result in Exception.

Related

Java CSV printing relevant information in relation to User input

my current code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Scanner;
public class Menu {
private static final String DEFAULT_DATE_FORMAT = "MM/dd/yyyy";
public static void main(String[] args) {
boolean exit = false;
int userInputt;
do {
userInputt = printMenu();
switch(userInputt) {
case 1:
inputLocation();
break;
case 2:
inputType();
break;
case 3:
inputRating();
break;
case 4:
System.out.println("Goodbye!");
exit = true;
break;
default:
System.out.println("Invalid Option.");
break;
}
}
/* an int varible that allows the storing of an integer */
while(userInputt > 4);
}
/* an int varible that allows the storing of an integer */
public static int printMenu () {
int selection;
Scanner sc = new Scanner (System.in);
System.out.println("Welcome to Melbnb!");
System.out.println("------------------------------------------------");
System.out.println("> Select from main menu");
System.out.println("------------------------------------------------");
System.out.println(" 1) Search by location");
System.out.println(" 2) Browse by type of place");
System.out.println(" 3) Filter by rating");
System.out.println(" 4) Exit");
System.out.print("Please Select: ");
selection = sc.nextInt();
return selection;
}
private static char inputLocation() {
Scanner userInput = new Scanner(System.in);
File file = new File("C:/Users/andys/OneDrive/Desktop/Melbnb (2).csv");
String fileData = "";
try (Scanner reader = new Scanner(file)) {
// Read the header line so we don't deal with it again
fileData = reader.nextLine();
System.out.print("Please provide a location: ");
String location1 = userInput.nextLine().trim();
List<String> foundRecords = new ArrayList<>();
boolean found = false;
while (reader.hasNextLine()) {
fileData = reader.nextLine().trim();
// Skip blank lines (if any).
if (fileData.isEmpty()) {
continue;
} String regex = ",";
String[] lineParts = fileData.split(regex);
found = (location1.isEmpty() ||
(lineParts[0].contains(location1) ||
(location1.isEmpty() ||
(lineParts[1].contains(location1)))));
if (found) {
foundRecords.add(fileData);
found = false;
}
}
// Display found records (if any)
System.out.println();
System.out.println("Found Records:");
System.out.println("====================================");
if (foundRecords.isEmpty()) {
System.out.println(" No Records Found!");
}
else {
for (String str : foundRecords) {
System.out.println(str);
}
}
System.out.println("====================================");
}
catch (FileNotFoundException ex) {
}
char userInputt;
do {
userInputt = location();
switch(userInputt) {
case 1:
System.out.println("------------------------------------------------");
break;
case 2:
inputType();
break;
case 3:
inputRating();
break;
case 4:
printMenu();
break;
default:
break;
}
}
while(userInputt > 4);
return userInputt;
}{
}
private static char location() {
// TODO Auto-generated method stub
return 0;
}
private static void inputType() {
System.out.println("------------------------------------------------");
}
private static void inputRating() {
}
/* ---------------------------------- Locations ---------------------------------- */
private static void Southbank() {
int southbankPrice = 42;
int southbankClean = 11;
int southbankService = 10;
double southbankDiscount = 0.05;
Scanner checkIn = new Scanner (System.in);
System.out.println("------------------------------------------------");
System.out.println("> Provide dates");
System.out.println("------------------------------------------------");
System.out.print("Please provide check-in date (dd/mm/yyyy): ");
Date inDate = getInputDate(checkIn);
System.out.print("Please provide checkout date (dd/mm/yyyy): ");
Date outDate = getInputDate(checkIn);
System.out.println("------------------------------------------------");
Scanner pInfo = new Scanner (System.in);
System.out.println("> Provide personal information");
System.out.println("------------------------------------------------");
System.out.print("Please provide your given name: ");
String southName = pInfo.nextLine();
System.out.print("Please provide your surname: ");
String southLast = pInfo.nextLine();
System.out.print("Please provide your email address: ");
String southEmail = pInfo.nextLine();
System.out.print("Please provide number of guests: ");
String southGuest = pInfo.nextLine();
System.out.print("Confirm and pay (Y/N): ");
String southConfirm = pInfo.nextLine();
System.out.println("------------------------------------------------");
System.out.println("> Show property details");
System.out.println("------------------------------------------------");
System.out.printf("%-25s%-20s\n", "Property:","Private room in the heart of Southbank hosted by " + southName);
System.out.printf("%-25s%-20s\n", "Type of place:","Private room");
System.out.printf("%-25s%-20s\n", "Location:","Southbank");
System.out.printf("%-25s%-20s\n", "Rating:","4.5");
System.out.printf("%-25s%-20s\n", "Description:","The apartment is situated in the heart of Southbank with an easy access to shops and cafes. It has a warm and spacious living room with an amazing view of the gardens.");
System.out.printf("%-25s%-20s\n", "Number of guests: ", southGuest);
System.out.printf("%-25s%-20s\n", "Price:", "asd");
System.out.printf("%-25s%-20s\n", "Discounted price:","asd");
System.out.printf("%-25s%-20s\n", "Service fee:","asd");
System.out.printf("%-25s%-20d\n", "Cleaning fee: ", southbankClean );
System.out.printf("%-25s%-20s\n", "Total:","asd");
}
/* ---------------------------------- Date Validation ---------------------------------- */
private static Date getInputDate(final Scanner checkIn) {
try {
return new SimpleDateFormat(DEFAULT_DATE_FORMAT).parse(checkIn.nextLine());
} catch (ParseException ex) {
System.out.println("Invalid Date. Please Try again!");
Southbank();
}
return null;
}
}
The first image is my Desired output
The second is my current output
and the third image is my CSV
My program has a feature which will allow the user to a hotel apartment by inputting a specific location for example 'South', as shown in the screenshots of my current output once the term 'South' gets inputted to prints out all the columns for any fields relating to the search term in the CSV file, However i only want the first column to be printed out. How can i achieve this output?
What can i do to achieve my desired output?
I have tried removing the 'for' statement in the following code and replacing the print element with foundrecords.get(0)

Read empty line in text file

if I want to read file from text file and store it in an array,each line goes to correct array
this is the text file
111111,34,24.5,first line
222222,53,22.0,second line
333333,,32.0,third line
44444,22,12.6,
if line is empty through exception saying "title is missing" or something like that.
a code has been made if the array length==4 then display lines in order but if length less than 4 and line is missing throw exception but when I want to put last array[3] gives me error. have a look if you can seethe error that would help
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Itry {
public static void main(String[] args) {
// TODO Auto-generated method stub
String [] splitArray = new String[4];
String line = "";
String array1, description;
int number;
double price;
// Total sales
double total = 0;
Scanner keyboard = new Scanner (System.in);
// Allow the user to enter the name of text file that the data is stored in
System.out.println("This program will try to read data from a text file ");
System.out.print("Enter the file name: ");
String filename = keyboard.nextLine();
Scanner fileReader = null;
try {
File Fileobject = new File (filename);
fileReader = new Scanner (Fileobject);
System.out.println("\nTransactions");
System.out.println("================");
while(fileReader.hasNext())
{
// Contains stock code,Quantity,Price,Description
line = fileReader.nextLine();// Read a line of data from text file
splitArray = line.split(",");
// check to make sure there are 4 parts in splitArray
if(splitArray.length == 4)
{
// remove spaces
splitArray[0] = splitArray[0].trim();
splitArray[1] = splitArray[1].trim();
splitArray[2] = splitArray[2].trim();
splitArray[3] = splitArray[3].trim();
// Extract each item into an appropriate
// variable
try {
array1 = splitArray[0];
number = Integer.parseInt(splitArray[1]);
price = Double.parseDouble(splitArray[2]);
description = splitArray[3];
// Output item
System.out.println("Sold "+String.format("%-5d", number) +
String.format("%-12s", description )+ " at "+"£"+
String.format("%-5.2f", price));
// Compute total
total += number * price;
} // end of try
catch(NumberFormatException e)
{
System.out.println("Error: Cannot convert to number");
}
} //end of if
else if (splitArray[0].length()<1) {
try { splitArray[0] = splitArray[0].trim();
System.out.println(" Title is missing "+" "+splitArray[1] +""+splitArray[2]+"");
}
catch(NumberFormatException e)
{
System.out.println("Error: Cannot convert to number");
}
}
else if (splitArray[1].length()<=1) {
try { splitArray[1] = splitArray[1].trim();
System.out.println(splitArray[0]+" "+" here is missing " +""+splitArray[2] );
}
catch(NumberFormatException e)
{
System.out.println("Error: Cannot convert to number");
}}
else if (splitArray[2].length()<=1) {
try { splitArray[2] = splitArray[2].trim();
System.out.println(splitArray[0]+" "+splitArray[1] +""+" here is missing "+splitArray[3]);
}
catch(NumberFormatException e)
{
System.out.println("Error: Cannot convert to number");
}}
else if (splitArray[3].length()<=1) {
try { splitArray[3] = splitArray[3].trim();
System.out.println(splitArray[0]+" "+splitArray[1] +""+splitArray[2]+"title is missing");
}
catch(NumberFormatException e)
{
System.out.println("Error: Cannot convert to number");
}}
}//end of while
System.out.printf("\nTotal sales: £"+String.format("%-6.2f", total));
}// end of try block
catch (FileNotFoundException e)
{
System.out.println("Error - File does not exist");
}
}
}
You can do it as follows:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] splitArray = new String[4];
String line = "";
String array1, description;
int number;
double price;
// Total sales
double total = 0;
Scanner keyboard = new Scanner(System.in);
// Allow the user to enter the name of text file that the data is stored in
System.out.println("This program will try to read data from a text file ");
System.out.print("Enter the file name: ");
String filename = keyboard.nextLine();
Scanner fileReader = null;
try {
File Fileobject = new File(filename);
fileReader = new Scanner(Fileobject);
System.out.println("\nTransactions");
System.out.println("================");
int count = 1;
while (fileReader.hasNext()) {
// Contains stock code,Quantity,Price,Description
line = fileReader.nextLine();// Read a line of data from text file
try {
if (line != null && line.length() > 0) {
splitArray = line.split(",");
// check to make sure there are 4 parts in splitArray
if (splitArray.length == 4) {
// remove spaces
splitArray[0] = splitArray[0].trim();
splitArray[1] = splitArray[1].trim();
splitArray[2] = splitArray[2].trim();
splitArray[3] = splitArray[3].trim();
// Extract each item into an appropriate variable
try {
array1 = splitArray[0];
number = Integer.parseInt(splitArray[1]);
price = Double.parseDouble(splitArray[2]);
description = splitArray[3];
// Output item
System.out.println(
"Sold " + String.format("%-5d", number) + String.format("%-12s", description)
+ " at " + "£" + String.format("%-5.2f", price));
// Compute total
total += number * price;
} catch (NumberFormatException e) {
System.out.println("Error in line#" + count + ": insufficient/invalid data");
}
} else {
throw new IllegalArgumentException(
"Error in line#" + count + ": insufficient/invalid data");
}
} else {
throw new IllegalArgumentException("Line#" + count + " is empty");
}
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
count++;
} // end of while
System.out.printf("\nTotal sales: £" + String.format("%-6.2f", total));
} catch (FileNotFoundException e) {
System.out.println("Error - File does not exist");
}
}
}
A sample run:
This program will try to read data from a text file
Enter the file name: data2.txt
Transactions
================
Sold 34 Apple at £24.50
Line#2 is empty
Sold 53 Mango at £22.00
Line#4 is empty
Error in line#5: insufficient/invalid data
Line#6 is empty
Error in line#7: insufficient/invalid data
Total sales: £1999.00
Content of data2.txt:
111111,34,24.5,Apple
222222,53,22.0,Mango
333333,,32.0,Orange
44444,22,12.6,

java having trouble with multiple classes

so I'm trying to use a switch so that when i click on a range of 1 to 4, each one is directed to a class and performs its function. The choice "1" should asks for the user to input the id, name, other name and marks, then calculate it's average. The second class should then display all the information and I'm not sure how to do it.
Here is my main code:
public class lab3q1 {
public static void main (String args[]){
Scanner sc = new Scanner(System.in);
Entries entriesobject = new Entries(); //object declaration
display displayobject = new display(); //object declaration
displayall displayallobject = new displayall(); //object declaration
sortdata sortdataobject = new sortdata();
System.out.println("1. Add new entries: ");
System.out.println("2. Display an entry: ");
System.out.println("3. Display all entries: ");
System.out.println("4. Sort Data: ");
System.out.println("5. Exit: ");
int s = sc.nextInt();
switch(s){
case 1:{
if(s==1)
try{
entriesobject.method0();
}
catch(Exception e){
System.out.println("You can't do that");
}
}
case 2:{
if(s==2){
try{
displayobject.method();
}
catch(Exception e){
System.out.println("You can't do that");
}
}
}
case 3:{
if(s==3){
try{
displayallobject.method2();
}
catch(Exception e){
System.out.println("You can't do that");
}
}
}
case 4:{
if(s==4){
try{
sortdataobject.method3();
}
catch(Exception e){
System.out.println("You can't do that");
}
}
}
case 5:{
if(s==5){break;}
}
}
}
}
Here is the first class:
public class Entries {
public void method0(){
int total=0,total2;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the student id: ");
int id = sc.nextInt();
sc.nextLine();
System.out.println("Enter the student name: ");
String name = sc.nextLine();
System.out.println("Enter the student other names: ");
String othername = sc.nextLine();
for(int i=1;i<=4;i++){
System.out.println("Enter the student marks" +(i));
int mark = sc.nextInt();
total += mark;
total2 =total/4;
System.out.println("The average marks is: "+total2);
}
}
}
And here is my second class:
public class display {
public void method() {
int n;
Scanner sc = new Scanner(System.in);
System.out.println("Here is the student id: ");
}
}
As you can see i can't seem to link them.
To answer your question: when different classes want to know about data in other classes (aka fields of other objects), you need ways to access that, like:
public class Student {
private int id;
... methods to put a value into id
public int getId() { return id; }
and then some other class that has one more Student objects can do.
Beyond that: you are getting your "separation of concerns" wrong. You should have one class that uses a scanner to "collect" data from the user. This class creates various other objects; and puts the data from the user into those objects.
All your other classes do not have / need a scanner object. They get their data, for example as parameters to their constructor.
System.out.println("The id is: " + someStudentObject.getId());

Error in reading Input from DataInputStream in java

Firstly I have made a folder named juet and then I have made two packages inside that folder. First one is Student package which takes care of all the students in university
package juet.stud;
import java.io.IOException;
import java.io.DataInputStream;
public class Student {
String name;
public int roll_no;
int std;
char grade;
public Student() {
try (DataInputStream in = new DataInputStream(System.in)) {
System.out.println("Enter name of student:");
name = in.readUTF();
System.out.println("Enter roll no.:");
roll_no = in.readInt();
System.out.println("Enter std:");
std = in.readInt();
System.out.println("Enter grade");
grade = in.readChar();
} catch (IOException e) {
System.err.println(e);
}
}
public void showInfo() {
System.out.println("Name of student: " + name);
System.out.println("Roll no.: " + roll_no);
System.out.println("Std: " + std);
System.out.println("Grade: " + grade);
}
}
Another package which I have made is Staff which takes care of all staff in the university
package juet.staff;
import java.io.IOException;
import java.io.DataInputStream;
public class Staff {
public int id;
String name, specialization;
char group;
public Staff() {
try (DataInputStream in = new DataInputStream(System.in)) {
System.out.println("Enter id:");
id = in.readInt();
System.out.println("Enter name:");
name = in.readUTF();
System.out.println("Enter area of specialization:");
specialization = in.readUTF();
System.out.println("Enter group");
group = in.readChar();
} catch (IOException e) {
System.err.println(e);
}
}
public void showInfo() {
System.out.println("ID: " + id);
System.out.println("Name: " + name);
System.out.println("Area of specialization: " + specialization);
System.out.println("Group: " + group);
}
}
And then at the last I have made MyUniversity Class in which I was using both the packages
package juet;
import juet.stud.Student;
import juet.staff.Staff;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.Console;
class University {
Student[] stu;
Staff stf[];
int studCount, staffCount;
University() {
try (DataInputStream in = new DataInputStream(System.in)) {
System.out.println("Enter capacity for students:");
int x = Integer.parseInt(in.readLine());
//stu = new Student[x];
System.out.println("Enter capacity for staff:");
x = Integer.parseInt(in.readLine());
stf = new Staff[x];
studCount = staffCount = 0;
} catch (IOException e) {
System.err.println(e);
}
}
void newStudent() {
stu[studCount] = new Student();
studCount++;
}
void studInfo(int roll
) {
int i;
for (i = 0; i < studCount; i++) {
if (stu[i].roll_no == roll) {
stu[i].showInfo();
return;
}
}
System.out.println("No match found.");
}
void newStaff() {
stf[staffCount] = new Staff();
staffCount++;
}
void staffInfo(int id
) {
int i;
for (i = 0; i < staffCount; i++) {
if (stf[i].id == id) {
stf[i].showInfo();
return;
}
}
System.out.println("No match found.");
}
}
class MyUniversity {
public static void main(String args[]) throws IOException {
University juet = new University();
int ch;
DataInputStream in = new DataInputStream(System.in);
while (true) {
System.out.println("\tMAIN MENU\n");
System.out.println("1. Add student\n2. Add staff member\n3. Display info about specific student\n4. Display info about specific staff member\n0. Exit\n\tEnter your choice");
try {
ch = Integer.parseInt(in.readLine());
switch (ch) {
case 1:
juet.newStudent();
break;
case 2:
juet.newStaff();
break;
case 3:
System.out.println("Enter roll no. of student to display info:");
int roll = in.readInt();
juet.studInfo(roll);
break;
case 4:
System.out.println("Enter ID of staff member to display info:");
int id = in.readInt();
juet.staffInfo(id);
break;
case 0:
return;
default:
System.out.println("Incorrect choice.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Problem is arising when I am calling University object in the main class it is asking for two inputs
1).Enter capacity for students
so I enter 3
and again it ask for
2)Enter capacity for staff
But when I enter the integer there it is running infinite times
and showing error
java.io.Exception:Stream closed
at
java.io.BufferedInputStream.getBufIfopen(BufferedInputStream.java:170)
atjuet.MyUniversity.main(MyUniversity.java:76)
at java.io.DataInputStream.readLine(DataInputStream.java:513)
Please help me Thanks in advance
You are using the wrong class. DataInputStream and the methods readUTF() and readInt() can not be used for reading text from the console. It is designed to read binary content encoded by a different Java program using DataOutputStream.
The following question and answers show you how to do it right:
How can I read input from the console using the Scanner class in Java?

InputMismatchError after implementing boolean

I've implemented a boolean to a kennel system I'm developing in Java and I'm getting an InputMismatchError when loading the data from the file.
I've read through a few times and tried to work it out but the solutions I'm trying aren't working. So far I've:
restructured the read in method (initialise) to read the data in properly and in the correct order, then assign it the newPet (local variable) in the correct order.
I then read through the .txt file (below) and made sure everything corresponded the the correct data, strings are being read as strings, ints as ints etc and that hasn't helped.
Can anybody spot the problem that's through the InputMismatch here?
Here is the error:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextBoolean(Unknown Source)
at KennelDemo.initialise(KennelDemo.java:79)
at KennelDemo.main(KennelDemo.java:337)
with line 79 and 337 being:
boolean mutualBoolean = infile.nextBoolean(); //and
demo.initialise();
Main class (apologises for the length)
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
public class KennelDemo {
private String filename; // holds the name of the file
private Kennel kennel; // holds the kennel
private Scanner scan; // so we can read from keyboard
private String tempFileName;
private String dogsFile = "dogs.txt";
private String catsFile = "cats.txt";
/*
* Notice how we can make this private, since we only call from main which
* is in this class. We don't want this class to be used by any other class.
*/
private KennelDemo() {
scan = new Scanner(System.in);
boolean fileCorrect = false;
do {
System.out.print("Which animal are you looking to check into the kennel?: " + "\n");
System.out.println("Dog");
System.out.println("Cat");
tempFileName = scan.next();
if(tempFileName.toLowerCase().equals("dog") || tempFileName.toLowerCase().equals("cat")) {
filename = tempFileName.toLowerCase().equals("dog") ? dogsFile : catsFile;
fileCorrect = true;
}
else {
System.out.println("That is not a valid filename, please enter either 'Dog' or 'cat' in lowercase.");
}
}
while(!fileCorrect);
}
/*
* initialise() method runs from the main and reads from a file
*/
private void initialise() {
kennel = new Kennel();
System.out.println("Using file " + filename);
// Using try-with-resource (see my slides from session 15)
try(FileReader fr = new FileReader(filename);
BufferedReader br = new BufferedReader(fr);
Scanner infile = new Scanner(br)){
String kennelName = infile.nextLine();
int kennelSize = infile.nextInt();
infile.nextLine();
kennel.setCapacity(kennelSize);
int numPets = infile.nextInt();
infile.nextLine();
kennel.setName(kennelName);
for(int i=0; i < numPets; i++){
String PetName = infile.nextLine();
int numOwners = infile.nextInt();
infile.nextLine();
ArrayList<Owner> owners = new ArrayList<>();
for(int oCount=0; oCount < numOwners; oCount++){
String name = infile.nextLine();
String phone = infile.nextLine();
Owner owner = new Owner(name, phone);
owners.add(owner);
}
boolean mutualBoolean = infile.nextBoolean();
infile.nextLine();
String favFood = infile.nextLine();
infile.nextLine();
int feedsPerDay = infile.nextInt();
Pet Pet = new Pet(PetName, owners, mutualBoolean, favFood, feedsPerDay);
kennel.addPet(Pet);
}
} catch (FileNotFoundException e) {
System.err.println("The file: " + " does not exist. Assuming first use and an empty file." +
" If this is not the first use then have you accidentally deleted the file?");
} catch (IOException e) {
System.err.println("An unexpected error occurred when trying to open the file " + filename);
System.err.println(e.getMessage());
}
}
/*
* runMenu() method runs from the main and allows entry of data etc
*/
private void runMenu() {
String response;
do {
printMenu();
System.out.println("What would you like to do:");
scan = new Scanner(System.in);
response = scan.nextLine().toUpperCase();
switch (response) {
case "1":
admitPet();
break;
case "2":
changeKennelName();
break;
case "3":
printPetsWithBones();
break;
case "4":
searchForPet();
break;
case "5":
removePet();
break;
case "6":
setKennelCapacity();
break;
case "7":
printAll();
break;
case "Q":
break;
default:
System.out.println("Try again");
}
} while (!(response.equals("Q")));
}
private void setKennelCapacity() {
// set the boolean to check if the user REALLY wants to change the kennel size. We can never be too careful.
// boolean doContinue = false;
// Turns out the boolean does nothing, go figure.
// Still the error check works perfectly, now just a case of losing the temporary data if the program isn't closed through the menu.
// Kennel currently doesn't save until you use "q" at the menu to save the information. Possible solutions?
// Hello? Is this thing on?
int currentKennelCapacity = kennel.getCapacity();
System.out.println("The current kennel holds " + currentKennelCapacity + ", are you sure you want to change the current kennel size?");
String userWantsToContinue;
userWantsToContinue = scan.nextLine().toUpperCase();
if(userWantsToContinue.equals("Y")){
// doContinue = true;
System.out.print("Please enter the new size of the kennel you'd like: ");
int max = scan.nextInt();
scan.nextLine();
kennel.setCapacity(max);
System.out.println("The new kennel size is " + max + ", we'll now return you to the main menu. Please make sure the quit the program at the end of your session to save any changes. \n");
}
else System.out.println("No problem, we'll return you back to the main menu. \n");
//Duplicate code that caused an error when running through the conditions above, saved in case of future reference.
/* System.out.print("Enter max number of Pets: ");
int max = scan.nextInt();
scan.nextLine();
kennel.setCapacity(max);
*/
}
private void printPetsWithBones() {
Pet[] PetsWithBones = kennel.obtainDogsWhoLikeBones();
System.out.println("Pets with bones: ");
for (Pet d: PetsWithBones){
System.out.println("Pet name: " + d.getName());
}
}
/*
* printAll() method runs from the main and prints status
*/
private void printAll() {
Pet[] allPets = kennel.displayAllPets();
for (Pet p: allPets){
System.out.println("Animal name: " + p.getName());
System.out.println("Original owner(s): " + p.getOriginalOwners());
if(filename.equals(dogsFile)){
System.out.println("Do they like bones? " + Dog.getLikesBones());
}
else if(filename.equals(catsFile)){
System.out.println("Can they share a run? " + Cat.getShareRun());
}
System.out.println("Favourite food: " + p.getFavouriteFood());
System.out.println("Feeds per day: " + p.getFeedsPerDay());
System.out.println("====================================");
}
}
/*
* save() method runs from the main and writes back to file
*/
private void save() {
try(FileWriter fw = new FileWriter(filename);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter outfile = new PrintWriter(bw);){
outfile.println(kennel.getName());
outfile.println(kennel.getCapacity());
outfile.println(kennel.getNumOfPets());
Pet[] Pets = kennel.obtainAllPets();
for (Pet d: Pets){
outfile.println(d.getName());
Owner[] owners = d.getOriginalOwners();
outfile.println(owners.length);
for(Owner o: owners){
outfile.println(o.getName());
outfile.println(o.getPhone());
}
// TODO outfile.println(d.getLikesBones());
outfile.println(d.getFeedsPerDay());
outfile.println(d.getFavouriteFood());
}
} catch (IOException e) {
System.err.println("Problem when trying to write to file: " + filename);
}
}
private void removePet() {
System.out.println("which Pet do you want to remove");
String Pettoberemoved;
Pettoberemoved = scan.nextLine();
kennel.removePet(Pettoberemoved);
}
private void searchForPet() {
String allNames = kennel.getName();
System.out.println("Current pet in the kennel: " + allNames + "\n");
System.out.println("Which pet would you like to get the details for?");
String name = scan.nextLine();
Pet Pet = kennel.search(name);
if (Pet != null){
System.out.println(Pet.toString());
} else {
System.out.println("Could not find Pet: " + name);
}
}
private void changeKennelName() {
String name = scan.nextLine();
kennel.setName(name);
}
private void admitPet() {
boolean mutualBoolean = false;
if(filename.equals(dogsFile)){
System.out.println("enter on separate lines: name, owner-name, owner-phone, do they like bones?, favourite food, number of times fed");
}
else if(filename.equals(catsFile)){
System.out.println("enter on separate lines: name, owner-name, owner-phone, can they share a run?, favourite food, number of times fed");
}
String name = scan.nextLine();
ArrayList<Owner> owners = getOwners();
if(filename.equals(dogsFile)){
System.out.println("Does he like bones? (Y/N)");
}
else if(filename.equalsIgnoreCase(catsFile)){
System.out.println("Can the cat share a run? (Y/N)");
}
String booleanCheck;
booleanCheck = scan.nextLine().toUpperCase();
if (booleanCheck.equals("Y")) {
mutualBoolean = true;
}
System.out.println("What is his/her favourite food?");
String fav;
fav = scan.nextLine();
System.out.println("How many times is he/she fed a day? (as a number)");
int numTimes;
numTimes = scan.nextInt(); // This can be improved (InputMismatchException?)
numTimes = scan.nextInt();
Pet newPet = new Pet(name, owners, mutualBoolean, fav, numTimes);
kennel.addPet(newPet);
System.out.println("Pet " + newPet.getName() + " saved.");
// Save when you add new Pet in case the program isn't closed via the correct menu.
// Everything will still save when case "q" is used though.
save();
}
private ArrayList<Owner> getOwners() {
ArrayList<Owner> owners = new ArrayList<Owner>();
String answer;
do {
System.out
.println("Enter on separate lines: owner-name owner-phone");
String ownName = scan.nextLine();
String ownPhone = scan.nextLine();
Owner own = new Owner(ownName, ownPhone);
owners.add(own);
System.out.println("Another owner (Y/N)?");
answer = scan.nextLine().toUpperCase();
} while (!answer.equals("N"));
return owners;
}
private void printMenu() {
if(filename.equals(catsFile)) {
System.out.println("1 - add a new cat ");
System.out.println("2 - set up Kennel name");
System.out.println("4 - search for a cat");
System.out.println("5 - remove a cat");
System.out.println("6 - set kennel capacity");
System.out.println("7 - print all cats");
System.out.println("q - Quit");
}
else if(filename.equals(dogsFile)) {
System.out.println("1 - add a new dog ");
System.out.println("2 - set up Kennel name");
System.out.println("3 - print all dogs who like bones");
System.out.println("4 - search for a dog");
System.out.println("5 - remove a dog");
System.out.println("6 - set kennel capacity");
System.out.println("7 - print all dogs");
System.out.println("q - Quit");
}
}
// /////////////////////////////////////////////////
public static void main(String args[]) {
System.out.println("**********HELLO***********");
KennelDemo demo = new KennelDemo();
demo.initialise();
demo.runMenu();
demo.printAll();
demo.save();
System.out.println("***********GOODBYE**********");
}
}
and here is the .txt file being read from:
DogsRUs // kennel name
20 // capacity
3 // number of pets
Rover //pet name
2 // number of owners
Chris Loftus // first owner
1234 // phone number
Pete Hoskins // second owner
2222 // phone number
1 // boolean for mutualBoolean
biscuits // favourite food
// NOTE: for some reason favFood wasn't being added but it wasn't causing an error at all, it's the boolean that's throwing the input error. Structure above repeats for the data below.
Dinky
1
James Bond
007007
1
Gold fingers
catTest
1
Billy
456789
1
Curry
Clearly the problem is the boolean being read in but I really can't see the solution to it at all unfortunately. When mutualBoolean was likeBones (originally the program was only being used to check dogs in rather than dogs and cats) it was working fine.
Here is the code I've used to inherit for the mutualBoolean that's being used
import java.util.ArrayList;
public class Pet {
protected ArrayList<Owner> originalOwners;
protected boolean mutualBoolean;
protected String petName;
protected String favFood;
protected int foodPerDay;
public Pet(String name, ArrayList<Owner> owners, boolean mutualBoolean, String food, int mealsPerDay) {
petName = name;
this.favFood = food;
this.foodPerDay = mealsPerDay;
originalOwners = new ArrayList<Owner>();
for(Owner o: owners){
Owner copy = new Owner(o.getName(), o.getPhone());
originalOwners.add(copy);
}
this.mutualBoolean = mutualBoolean;
}
public String getName() {
return petName;
}
public void setName(String newName) {
petName = newName;
}
/*protected boolean mutualBoolean() {
return mutualBoolean;
}*/
/**
* Returns a copy of the original owners
* #return A copy of the original owners as an array
*/
public Owner[] getOriginalOwners(){
Owner[] result = new Owner[originalOwners.size()];
result = originalOwners.toArray(result);
return result;
}
/**
* How many times a day to feed the dog
* #param feeds The number of feeds per day
*/
public void setFeedsPerDay(int feeds){
foodPerDay = feeds;
}
/**
* The number of feeds per day the dog is fed
* #return The number of feeds per day
*/
public int getFeedsPerDay(){
return foodPerDay;
}
/**
* What's his favourite food?
* #param food The food he likes
*/
public void setFavouriteFood(String food){
favFood = food;
}
/**
* The food the dog likes to eat
* #return The food
*/
public String getFavouriteFood(){
return favFood;
}
/**
* Note that this only compares equality based on a
* dog's name.
* #param The other dog to compare against.
*/
#Override
public boolean equals(Object obj) { // Generated by Eclipse to be more robust
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Dog other = (Dog) obj;
if (petName == null) {
if (other.petName != null)
return false;
} else if (!petName.equals(other.petName))
return false;
return true;
}
/**
* A basic implementation to just return all the data in string form
*/
public String toString() {
return "Dog name:" + petName + "Original Owner:" + originalOwners + "Favfood:" + favFood
+ "FoodPerDay:" + foodPerDay;
}
}
and the Dog class
import java.util.ArrayList;
public class Dog extends Pet {
public static boolean likesBones;
public Dog(String name, ArrayList<Owner> owners, String food, int mealsPerDay, boolean likeBones) {
super(name, owners, likeBones, food, mealsPerDay);
Dog.likesBones = likeBones;
}
/**
* Does the dog like bones?
* #return true if he does
*/
public static boolean getLikesBones() {
return likesBones;
}
}

Categories

Resources