Error in reading Input from DataInputStream in java - 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?

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)

NoSuchElementException ocurring inside the code

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.

Saving the ArrayList entries

Firstly here is my code.
postit.java file
package postit;
import java.util.Scanner;
class Postit {
public static Scanner menu = new Scanner(System.in);
public static void main(String[] args) {
int MenuOption = 0;
NewStorage G = new NewStorage(); // Case 1 Object
while(MenuOption != 3){
System.out.println(
"\n--------Note System-------\n" +
"----------------------------\n" +
"1. Create a Note \n" +
"2. View Notes \n" +
"3. Close Program\n" +
"----------------------------\n");
MenuOption = menu.nextInt();
menu.nextLine();
switch (MenuOption) {
case 1:
G.printinfo();
G.Notestore();
break;
case 2:
G.viewNotes();
G.printNotes();
break;
case 3:
System.out.println("Program is closing");
System.exit(0);
break;
default:
System.out.println("Invalid choice.");
break;
}
}
}
}
NewStorage.java file
package postit;
import java.util.Scanner;
import java.util.ArrayList;
class NewStorage {
ArrayList<Note> NoteArray = new ArrayList<Note>(20);
public void printinfo() {
System.out.println("--- Fill note here ---");
}
public void Notestore() {
System.out.println("Enter the note ID you wish to attach the note with\n\n");
String inputIDnote = Postit.menu.nextLine();
System.out.println("Enter your note\n\n");
String noteDescription = Postit.menu.nextLine();
NoteArray.add(new Note(inputIDnote, noteDescription));
}
public void viewNotes() {
System.out.println("Please enter the number of the note you wish to view.");
int count = 0;
for (int i = 0 ; i < NoteArray.size(); i++) {
System.out.println((count++) + ": " + NoteArray.get(i).inputIDnote);
}
}
public void printNotes(){
int count = Postit.menu.nextInt();
Postit.menu.nextLine();
System.out.println(count + " " + NoteArray.get(count));
}
}
note.java file
package postit;
class Note {
String inputIDnote;
String noteDescription;
public Note(String inputIDnote, String noteDescription) {
this.inputIDnote = inputIDnote;
this.noteDescription = noteDescription;
}
#Override
public String toString() {
return "ID: " + inputIDnote + " \n\nDescription: " + noteDescription;
}
}
So forgive me as I am learning how to write Java so this is one of my first programs, so if you think its badly written then you know why.
As you can see the program can ask the user if they would like to create a note which takes an ID and note itself. Then the user can view the notes created by choosing the number next to the listed note ID's. So when I close the program obviously the ArrayList is wiped. Is there a way to save the notes within the array list even after the program has closed? As I would like to implement an edit feature later so it would be a useful thing to have.

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;
}
}

End of File Error in File Handling Program

I am creating a database project in java using file handling. The program is working without compiling error. Following points are not working
File is storing only first record. (if program is running again it is overwriting file)
I want to display all records but the only first record is displaying with Exeception
Please offer suggestions..
import java.io.*;
public class Student implements Serializable
{
private int roll;
private String name; //To store name of Student
private int[] marks = new int[5]; //To store marks in 5 Subjects
private double percentage; //To store percentage
private char grade; //To store grade
public Student()
{
roll = 0;
name = "";
for(int i = 0 ; i < 5 ; i++)
marks[i] = 0;
percentage = 0;
grade = ' ';
}
public Student(int roll , String name ,int[] marks)
{
setData(roll,name,marks);
}
public void setData(int roll , String name ,int[] marks)
{
this.roll = roll;
this.name = name;
for(int i = 0 ; i < 5 ; i++)
this.marks[i] = marks[i];
cal();
}
//Function to calculate Percentage and Grade
private void cal()
{
int sum = 0;
for(int i = 0 ; i < 5 ;i++)
sum = sum + marks[i];
percentage = sum/5;
if(percentage>85)
grade = 'A';
else if(percentage > 70)
grade = 'B';
else if (percentage >55)
grade = 'C';
else if (percentage > 33)
grade = 'E';
else
grade = 'F';
}
public char getGrade() { return grade; }
public double getPercentage() { return percentage; }
#Override
public String toString()
{
string format = "Roll Number : %4d, Name : -%15s "
+ "Percentage : %4.1f Grade : %3s";
return String.format(format, roll, name, percentage, grade);
}
}
second file
import java.io.*;
public class FileOperation
{
public static void writeRecord(ObjectOutputStream outFile, Student temp)
throws IOException, ClassNotFoundException
{
outFile.writeObject(temp);
outFile.flush();
}
public static void showAllRecords(ObjectInputStream inFile)
throws IOException, ClassNotFoundException
{
Student temp = new Student();
while(inFile.readObject() != null)
{
temp = (Student)inFile.readObject();
System.out.println(temp);
}
}
}
main file
(only two options are working)
import java.util.*;
import java.io.*;
public class Project
{
static public void main(String[] args)
throws IOException,ClassNotFoundException
{
ObjectInputStream inFile;
ObjectOutputStream outFile;
outFile = new ObjectOutputStream(new FileOutputStream("info.dat"));
inFile = new ObjectInputStream(new FileInputStream("info.dat"));
Scanner var = new Scanner(System.in) ;
int roll;
String name;
int[] marks = new int[5];
int chc = 0;
Student s = new Student();
while(chc != 6)
{
System.out.print("\t\tMENU\n\n");
System.out.print("1.Add New Record\n");
System.out.print("2.View All Records\n");
System.out.print("3.Search a Record (via Roll Number) \n");
System.out.print("4.Delete a Record (via Roll Number) \n");
System.out.print("5.Search a Record (via Record Number)\n");
System.out.print("6.Exit\n");
System.out.print("Enter your choice : ");
chc = var.nextInt();
switch(chc)
{
case 1:
System.out.print("\nEnter Roll number of Student : ");
roll = var.nextInt();
System.out.print("\nEnter Name of Student : ");
name = var.next();
System.out.println("\nEnter marks in 5 subjects \n");
for(int i = 0 ; i < 5 ; i++)
{
System.out.print("Enter marks in subject " + (i+1) + " ");
marks[i] = var.nextInt();
}
s.setData(roll , name , marks );
System.out.println("\n Adding Record to file \n");
System.out.printf("Record \n " + s);
System.out.println("\n\n");
FileOperation.writeRecord(outFile,s);
System.out.println("Record Added to File\n ");
break;
case 2:
System.out.println("All records in File \n");
FileOperation.showAllRecords(inFile);
break;
default: System.out.println("Wrong choice ");
}
}
outFile.close();
inFile.close();
}
}
Your program found a ClassNotFoundException and your method only throws an IOException.
I would check your import statements to make sure you are bringing in the class for ObjectInputStream
import java.io.ObjectInputStream;
If you want to get rid of unreported exception try:
Try
public static void showAllRecords(ObjectInputStream inFile) throws IOException, ClassNotFoundException

Categories

Resources