How to read/writetwo HashMap objects to file in Java? - java

I've been working on a project where I need to write two hash maps to a .dat file in Java. I need to be able to add, remove, and modify an employeeMap hashmap and then write it to a file, and likewise for the other gradeMap HashMap. I don't have any issues adding, removing, or modifying the hashmaps themselves, but I am struggling to write the code to be able to write the objects to a file and read the objects from a file. Here's the class code and main code.
import java.io.Serializable;
//class code
public class Employee implements Comparable<Employee>, Serializable
{
/**
*
*/
private static final long serialVersionUID = 1L;
private String fname;
private String lname;
private int ID;
/**
* default constructor for the employee class
*/
Employee()
{
setFname("");
setLname("");
setID(0);
}
/**
*
* #param ln last name
* #param fn first name
* #param id ID number
*/
Employee(String ln, String fn, int id)
{
setFname(fn);
setLname(ln);
setID(id);
}
/**
*
* #return first name of the employee
*/
public String getFname() {
return fname;
}
/**
*
* #param fname first name of the employoee
*/
public void setFname(String fname) {
this.fname = fname;
}
/**
*
* #return last name of the employee
*/
public String getLname() {
return lname;
}
/**
*
* #param lname last name of the employee
*/
public void setLname(String lname){
this.lname = lname;
}
/**
*
* #return ID number
*/
public int getID(){
return ID;
}
/**
*
* #param iD id number
*/
public void setID(int iD)
{
this.ID = iD;
}
public boolean equals(Object obj)
{
if(this == obj)
return true;
else if(obj == null)
return false;
else if(obj instanceof Employee)
{
Employee o = (Employee) obj;
return this.fname.equals(o.fname) && this.lname.equals(o.lname) && this.ID == o.ID;
}
else
return false;
}
public int hashCode()
{
final int HASH_MULTIPLIER = 29;
int h = HASH_MULTIPLIER * fname.hashCode() + lname.hashCode();
h = HASH_MULTIPLIER * h + ((Integer) ID).hashCode();
return h;
}
#Override
public int compareTo(Employee e)
{
if(this.lname.compareTo(e.lname) == 0)
{
if(this.fname.compareTo(e.fname) == 0 )
{
if(this.ID > e.ID)
return 1;
else if(this.ID == e.ID)
return 0;
else
return -1;
}
}
return this.lname.compareTo(e.lname);
}
public String toString()
{
return("Last Name: " + lname + "\nFirst Name: " + fname + "\nID: " + ID);
}
}
Main Code
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.io.ObjectOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
public class Main {
private static Scanner in = new Scanner(System.in);
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException
{
Map <Integer,Employee> employeeMap;
Map <Employee, Integer> gradeMap;
File f = new File("Employee.dat");
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(f));
if(f.exists())
{
try(ObjectInputStream in = new ObjectInputStream(new FileInputStream(f)))
{
employeeMap = (HashMap<Integer,Employee>) in.readObject();
gradeMap = (HashMap<Employee,Integer>) in.readObject();
}
catch(Exception e)
{
employeeMap = new HashMap<Integer, Employee>();
gradeMap = new HashMap<Employee, Integer>();
}
}
else
{
employeeMap = new HashMap<Integer, Employee>();
gradeMap = new HashMap<Employee, Integer>();
}
int choice = 0;
do
{
choice = printMenuAndGetChoice();
switch(choice)
{
case 1:
addEmployee(employeeMap, gradeMap);
out.writeObject(gradeMap);
out.close();
break;
case 2:
removeEmployee(employeeMap, gradeMap);
out.writeObject(employeeMap);
out.writeObject(gradeMap);
break;
case 3:
modifyEmployee(employeeMap, gradeMap);
out.writeObject(employeeMap);
out.writeObject(gradeMap);
break;
case 4:
display(gradeMap);
break;
case 5:
break;
default:
break;
}
} while(choice != 5);
}
public static int printMenuAndGetChoice()
{
int choice = 0;
System.out.println("1) Add an employee");
System.out.println("2) Remove an employee");
System.out.println("3) Modify information for an employee");
System.out.println("4) Print employees");
System.out.println("5) Exit");
System.out.println("Choice: ");
choice = in.nextInt();
return choice;
}
public static void addEmployee(Map<Integer, Employee> employeeMap, Map<Employee, Integer> gradeMap)
{
Employee newEmployee = new Employee();
System.out.println("Enter the last name for this employee");
newEmployee.setLname(in.next());
System.out.println("Enter the first name for this employee");
newEmployee.setFname(in.next());
System.out.println("Enter the ID for this employee");
newEmployee.setID(in.nextInt());
System.out.println("Enter the work performance value (1 - 5) for this employee");
int performance = in.nextInt();
int x = 0;
Set<Employee> empList = gradeMap.keySet();
for(Employee e: empList)
if(e.equals(newEmployee))
{
System.out.println("Employee already exists!\n");
break;
}
int hash = newEmployee.getID() * newEmployee.hashCode();
employeeMap.put(hash, newEmployee);
gradeMap.put(newEmployee, performance);
}
public static void removeEmployee(Map<Integer, Employee> employeeMap, Map<Employee, Integer> gradeMap)
{
System.out.println("\nEnter the ID number of the employee to be removed: ");
int id = in.nextInt();
if(!employeeMap.containsKey(id))
System.out.println("The employee does not exist.\n Please enter another ID");
else
{
System.out.println("Employee removed:" + employeeMap.get(id).getFname() + " " + employeeMap.get(id).getLname() + "\n");
gradeMap.remove(employeeMap.get(id));
employeeMap.remove(id);
}
}
public static void modifyEmployee(Map<Integer, Employee> employeeMap, Map<Employee, Integer> gradeMap)
{
Set<Employee> empList = gradeMap.keySet();
System.out.println("\nEnter the ID number of the employee to be removed: ");
int id = in.nextInt();
if(employeeMap.containsKey(id) == false)
System.out.println("The employee does not exist.\n Please enter another ID");
else
{
System.out.println("Enter the work performance value (1 - 5) for this employee");
int performance = in.nextInt();
gradeMap.put(employeeMap.get(id), performance);
}
}
public static void display(Map<Employee, Integer> gradeMap)
{
Set<Employee> empList = gradeMap.keySet();
for(Employee e: empList)
System.out.println(e.toString()+ " " + "\nPerformance: " + gradeMap.get(e) + "\n");
}
}
I've been referring to my textbook and online lecture notes and I can't seem to figure out the issue. Anyone have any ideas where I might be doing something wrong(I definitely am)? Thanks for the help.

Related

how to make fuction to allow me to delete a specific student

i want to add a function that allow me to delete a students
first this is the this the file student.java that contain the class student
, then the file called vstudent contain the ittrator and the array list to loop on the all students,then there is a file called Mainsystem contain the files handilling and functions to add students ,so i want to add fuction that allow me to delete a student.
import java.io.*;
import java.util.Scanner;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class student implements Serializable {
private int id;
private String name, email;
private int mobilenumber;
public student(int id, String name, String email, int mobilenumber) {
this.id = id;
this.name=name;
this.email = email;
this.mobilenumber = mobilenumber;
}
public int getId() {
return id;
}
#Override
public String toString() {
return "student{" +
"id=" + id +
", name='" + name + '\'' +
", email='" + email + '\'' +
", mobilenumber=" + mobilenumber +
'}';
}
}
import java.io.*;
import java.io.File.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.io.Serializable;
import java.util.Scanner;
public class vstudent extends Object implements Serializable {
private List<student> coll;
public vstudent() {
coll = new ArrayList<student>();
}
public void addstudent(student stu){
coll.add(stu);
}
#Override
public String toString() {
String total = "\n";
Iterator<student> i = coll.iterator();
while (i.hasNext()){
student s = (student) i.next();
total= total+s.toString();
}
return total;
}
}
import java.util.List;
import java.util.Scanner;
import java.io.Serializable;
import java.io.*;
import java.util.Iterator;
class librarianmenu {
public static void librarianMenu() {
System.out.println("---------------(Librarian) - Library Management System-----------");
System.out.println("\nEnter 0 for load a library" + "\nEnter 1 for save and quit" + "\nEnter 2 to add book"
+ "\nEnter 3 to list all books in library" + "\nEnter 4 to list all librarians");
}
}
public class Mainsystem {
static String fileName = null;
static library lib = new library();
static vstudent stu = new vstudent();
static librs librs = new librs();
static Scanner in = new Scanner(System.in);
static Boolean running = true;
public static void DisplayMainMenu() {
System.out.println("------------ Library Management System ------------");
System.out.println("Enter #: Switch to Admin Mode");
System.out.println("Enter $: Switch to Student Mode");
System.out.println("Enter <: Exit");
}
public static void main(String[] args) {
DisplayMainMenu();
Scanner in = new Scanner(System.in);
boolean shouldContinue = true;
while (true) {
String optionSelected = in.next();
if (!optionSelected.equals("<")) {
if (optionSelected.equals("#")) {
Admin admin = new Admin();
System.out.print("Enter Password: ");
String tempPassword = in.next();
System.out.println(tempPassword);
if (tempPassword.equals(admin.getPassword())) {
boolean isCorrectPassword = true;
while (isCorrectPassword) {
admin.displayMenu();
int adminInput = in.nextInt();
switch (adminInput) {
case 0: {
System.out.println("Enter the file name to load");
loadScript(in.next());
break;
}
case 1: {
addstudent();
break;
}
case 2: {
addlibrarians();
break;
}
case 3: {
System.out.println(stu.toString());
break;
}
case 4: {
saveandquit();
break;
}
case 5: {
System.out.print("Enter new password:");
String pass = in.next();
admin.setPassword(pass);
break;
}
case 6: {
isCorrectPassword = false;
DisplayMainMenu();
}
}
}
} else {
DisplayMainMenu();
}
} else if (optionSelected.equals("$")) {
librarianmenu menu = new librarianmenu();
while (running) {
librarianmenu.librarianMenu();
int studentInput = in.nextInt();
switch (studentInput) {
case 0: {
System.out.println("Enter the file name to load");
loadScript(in.next());
break;
}
case 1: {
saveandquit();
break;
}
case 2: {
addBook();
break;
}
case 3: {
System.out.println(lib.toString());
break;
}
case 4: {
System.out.println(librs.toString());
}
}
}
} else { //User chooses to Exit
break;
}
}
}
}
private static void addBook () {
int id;
String title, author;
int Available_quantity;
int issued_quantity;
System.out.println("\nEnter book name");
title = in.next();
System.out.println("\nEnter book Author");
author = in.next();
System.out.println("\nEnter book id");
id = in.nextInt();
System.out.println("\nEnter Available quantity");
Available_quantity = in.nextInt();
System.out.println("\nEnter issued_quantity");
issued_quantity = in.nextInt();
Book b = new Book(id, title, author, Available_quantity, issued_quantity);
lib.addBook(b);
}
private static void addstudent () {
int id;
String name, email;
int mobilenumber;
System.out.println("\nEnter student name");
name = in.next();
System.out.println("\nEnter student email");
email = in.next();
System.out.println("\nEnter student id");
id = in.nextInt();
System.out.println("\nEnter mobile number ");
mobilenumber = in.nextInt();
student s = new student(id, name, email, mobilenumber);
stu.addstudent(s);
}
private static void addlibrarians () {
int id;
String name;
int password;
System.out.println("\nEnter librarian name");
name = in.next();
System.out.println("\nEnter librarian id");
id = in.nextInt();
System.out.println("\nEnter password ");
password = in.nextInt();
librarians libras = new librarians(id, name, password);
librs.addlibrs(libras);
}
private static void saveandquit () {
System.out.println("Enter file name:");
fileName = in.next() + ".ser";
running = false;
FileOutputStream fos = null;
ObjectOutputStream out = null;
try {
fos = new FileOutputStream(fileName);
out = new ObjectOutputStream(fos);
out.writeObject(lib);
out.writeObject(stu);
fos.close();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void loadScript (String name){
FileInputStream fis = null;
ObjectInputStream in = null;
File file = new File(name + ".ser");
if (file.exists()) {
try {
fis = new FileInputStream(file);
in = new ObjectInputStream(fis);
try {
lib = (library) in.readObject();
stu = (vstudent) in.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
fis.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("\nThe file does not exist!");
}
}
}
As I can see , You use List from which you want to delete element,
In Java if you want to delete element you need to provide its id ,
Syntax :
StudentList.remove(idStudent)
for you i think you want to find a way to get the ID of the student you want to delete this is a way:
private static void deleteStudent () {
System.out.println("\nEnter ID of the student you want to delete ");
idStudent = in.nextInt();
for( Student st : stu){
if(st.getID()==idStudent){
stu.remove(idStudent);
}
}
}

Error of "variable might not initialized" while trying to use a class object as a parameter of a method, tried to use a IF to avoid the problem (JAVA)

I'm learning JAVA and I was making the code for a product sales system in a store as an example. So I created the Product, Customer and Sale classes.
In my menu I check if there is a registered product or customer, if yes I call my sales method that has both parameters. However, NetBeans notifies an error that the variable has not been initialized even with the logic not to start the sale if the registration has not been done before.
My basic code:
"variable product might not have been initialized"
"variable customer might not have been initialized"
//Main
//Reg a client and a product, then perform a sale.
package store;
import java.util.Random;
import java.util.Scanner;
public class Store {
static boolean flagProduct=false, flagCustomer=false;
public static void main(String[] args) {
menu();
}
public static void menu() {
System.out.println("\n Choose option:\n"
+ "1 - Product Registration\n"
+ "2 - Customer Registration\n"
+ "3 - Sell\n"
+ "4 - End\n"
);
Scanner scanner = new Scanner(System.in);
int select = scanner.nextInt();
switch (select) {
case 1:
Product product = RegistProduct();
System.out.print("\n Cod product : " + product.getCodProduct());
System.out.print("\n Price product : " + product.getPriceProduct());
System.out.print("\n Quantity product : " + product.getQuantProduct());
menu();break;
case 2:
Customer customer = RegistCustomer();
System.out.print("\n Cod Customer : " + customer.getCodCustomer());
System.out.print("\n Customer name: " + customer.getName());
menu();break;
case 3:
if(flagProduct == true && flagCustomer==true){
Sale sale = sell(product, customer); // *****where the error happens*****
System.out.print("\n Sale code : " + sale.getCodSale());
System.out.print("\n Customer name: " + customer.getName());
System.out.print("\n Cod product : " + product.getCodProduct()+ " -- Quantity:" + sale.getQuantSale()+ " -- Total:" + sale.getValueSale());
} else if(flagProduct == true && flagCustomer==false){
System.out.println("First register the customer ");
menu();break;
} else if(flagProduct == false && flagCustomer==true){
System.out.println("First register the product");
menu();break;
} else
System.out.println("First register the customer and product");
menu();break;
case 4:
break;
default:
System.out.println("Error");
menu();
}
}
public static Product RegistProduct(){
Product product = new Product();
java.util.Scanner scanner = new Scanner(System.in);
System.out.print("Product code:\n");
product.setCodProduct(scanner.nextInt());
System.out.print("Product price:\n");
product.setPriceProduct(scanner.nextFloat());
System.out.print("Product quantity:\n");
product.setQuantProduct(scanner.nextInt());
flagProduct = true;
return product;
}
public static Customer RegistCustomer(){
Customer customer = new Customer();
java.util.Scanner scanner = new Scanner(System.in);
System.out.print("Customer name:\n");
customer.setName(scanner.nextLine());
System.out.print("Customer code:\n");
customer.setCodCustomer(scanner.nextInt());
flagCustomer=true;
return customer;
}
public static Sale Sell(Product product, Customer customer){
java.util.Scanner scanner = new Scanner(System.in);
Random num = new Random();
int codSale = num.nextInt(9999);
Sale sale = new Sale();
sale.setCodSale(codSale);
System.out.print("Customer code:");
int codSaleCustomer = scanner.nextInt();
while (codSaleCustomer != customer.getCodCustomer()){
System.out.print("Non-existent code. Please enter a valid code:\n");
codSaleCustomer = scanner.nextInt();
}
System.out.print("Product code:");
int codSaleProduct = scanner.nextInt();
while (codSaleProduct != product.getCodProduct()){
System.out.print("Non-existent code. Please enter a valid code:\n");
codSaleProduct = scanner.nextInt();
}
System.out.print("Quantity of products purchased:\n");
sale.setQuantSale(scanner.nextInt());
sale.setValueSale(sale.getQuantSale()*product.getPriceProduct());
product.setQuantProduct(product.getQuantProduct() - sale.getQuantSale());
System.out.print("Remaining quantity in stock: "+ product.getQuantProduct());
return sale;
}
}
//Class Product
package store;
public class Product {
private int codProduct;
private float priceProduct;
private int quantProduct;
public int getCodProduct() {
return codProduct;
}
public void setCodProduct(int codProduct) {
this.codProduct = codProduct;
}
public float getPriceProduct() {
return priceProduct;
}
public void setPriceProduct(float priceProduct) {
this.priceProduct = priceProduct;
}
public int getQuantProduct() {
return quantProduct;
}
public void setQuantProduct(int quantProduct) {
this.quantProduct = quantProduct;
}
}
//Class customer
package store;
public class Customer {
private int codCustomer;
private String name;
public int getCodCustomer() {
return codCustomer;
}
public void setCodCustomer(int codCustomer) {
this.codCustomer = codCustomer;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
//Class sale
package store;
public class Sale extends Product{ //I dnno if extends is necessary
private int codSale;
private int quantSale;
private float valueSale;
public int getCodSale() {
return codSale;
}
public void setCodSale(int codSale) {
this.codSale = codSale;
}
public int getQuantSale() {
return quantSale;
}
public void setQuantSale(int quantSale) {
this.quantSale = quantSale;
}
public float getValueSale() {
return valueSale;
}
public void setValueSale(float valueSale) {
this.valueSale = valueSale;
}
}

How to Choose more than one item in method in java

I have just created a senario that looping which was I have to choose columns what I have selected from data base like this javaMain which have the senario
package myrestorderproject;
import enitities.Menu;
import enitities.Tables;
import java.awt.List;
import java.util.ArrayList;
import java.util.Scanner;
/**
*
* #author DELL
*/
public class MyRestOrderProject {
private static Scanner input;
public static void main(String[] args) {
// TODO code application logic here
input = new Scanner(System.in);
System.out.println("*-*-*-*-*-*Welcome to MyRestaurant*-*-*-*-*-*\n");
System.out.println("Please Choose Table From Tables List");
Tables t = new Tables();
t.getAllRows();
ArrayList<String> listItem = new ArrayList<String>();
boolean orderNotFinished = true;
while (orderNotFinished) {
System.out.print("Enter Table Number: ");
String tableNumber = input.nextLine();
boolean insertedTableNumber = db.goTodataBase.checkTableNumber(tableNumber);
if (insertedTableNumber) {
System.out.println("You Choose Table Number: " + tableNumber);
Menu m = new Menu();
m.getAllRows();
while (orderNotFinished) {
System.out.println("Please Choose Item From Menu List");
input = new Scanner(System.in);
String itemChosen = input.nextLine();
boolean insertedMenuItemId = db.goTodataBase.checkMenuItemInDB(itemChosen);
if (insertedMenuItemId) {
System.out.println("You Choose Item ID: " + itemChosen);
listItem.add(m.getAllRows(itemChosen));
System.out.print("Do you need to add more Items ? ");
String hasFinished = input.nextLine();
orderNotFinished = hasFinished.equals("yes");
} else {
System.out.println("Item Chosen doen't exist");
}
}
} else {
System.out.println("Table number does not exist");
}
}
}
}
I need now in the part which print "Please Choose Item From Menu List" after I choose the right Item Close the while loop,and I need also to choose more than one item that if I choose Items from menu give me the items was chosen with details getting from menu table
Like If I Choose Item ID 1 +Item ID 2 + Item ID 3 says that you have chosen
Item 1 Vegetable Pakora 20.00 veg Starters
Item 1 Vegetable Pakora 20.00 veg Starters
Item 1 Chicken Tikka 20.00 Non-veg Starters
after that exit the while loop
as every column have an ID, name, price, type and Category
and this method that am using in previous senario
public static boolean checkMenuItemInDB(String menuId) {
try {
setConnection();
Statement stmt = con.createStatement();
String strCheck = "select * from menu where "
+ "Menu_Id=" + menuId;
stmt.executeQuery(strCheck);
while (stmt.getResultSet().next()) {
return true;
}
} catch (Exception e) {
}
return false;
}
this is menu Class
package enitities;
import javax.swing.JTable;
/**
*
* #author DELL
*/
public class Menu {
private int Menu_Id;
private String Name;
private float Price;
private String Type;
private String Category;
public int getMenu_Id() {
return Menu_Id;
}
public void setMenu_Id(int Menu_Id) {
this.Menu_Id = Menu_Id;
}
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public float getPrice() {
return Price;
}
public void setPrice(float Price) {
this.Price = Price;
}
public String getType() {
return Type;
}
public void setType(String Type) {
this.Type = Type;
}
public String getCategory() {
return Category;
}
public void setCategory(String Category) {
this.Category = Category;
}
public void getAllRows() {
db.goTodataBase.printData("menu");
}
public String getAllRows(String itemChosen) {
db.goTodataBase.printData("menu");
return itemChosen;
}
}
this is a method which I calls in getAllRows
public static void printData(String tableNameOrSelectStatement) {
try {
setConnection();
Statement stmt = con.createStatement();
ResultSet rs;
String strSelectPart = tableNameOrSelectStatement.substring(0, 4).toLowerCase();
String strSelect;
if ("select ".equals(strSelectPart)) {
strSelect = tableNameOrSelectStatement;
} else {
strSelect = "select * from " + tableNameOrSelectStatement;
}
rs = stmt.executeQuery(strSelect);
ResultSetMetaData rsmd = rs.getMetaData();
int c = rsmd.getColumnCount();
while (rs.next()) {
for (int i = 1; i <= c; i++) {
if (i > 1) {
System.out.print(", ");
}
String columnValue = rs.getString(i);
// System.out.print(columnValue + " " + rsmd.getColumnName(i));
System.out.print(columnValue + " ");
}
System.out.println("");
}
} catch (Exception e) {
Tools.msgBox(e.getMessage());
}
}
About the loop :
Programmer tips : You need to avoid as much as possible while(true)-loop.
In your case you could use a system of flag, it will look like :
boolean customerHasFinished = false;
while(!customerHasFinished){
...
//Do your stuff
...
System.out.print("Have you finished ? ");
String hasFinished = input.nextLine();
customerHasFinished = hasFinished.equals("yes");
}
About multiple items :
The best way to store multiple items is to use collection.
In your case, you will probably need to create a Java class that represent an Item. Having fields like name, cost, etc. And then create a collection of Item.
An example with an ArrayList :
List<Item> listItem = new ArrayList<Item>();
boolean orderNotFinished = true;
while (orderNotFinished) {
System.out.println("Please Choose an Item From Menu List");
input = new Scanner(System.in);
String itemChosen = input.nextLine();
boolean insertedMenuItemId = db.goTodataBase.checkMenuItemInDB(itemChosen);
if (insertedMenuItemId) {
System.out.println("You Choose Item ID: " + itemChosen);
listItem.add(Item.getItemByName(itemChosen)); //Add the chosen item to the list
System.out.print("You want something else ? ");
String hasFinished = input.nextLine();
orderNotFinished = hasFinished.equals("yes");
}else {
System.out.println("Item Chosen doen't exist");
}
}

Change the data from a deserialization code

I just wanna to know how can I change the data from a deserialization. My program needs to:
Asks the user if they want to change the students information and stores that new data in the text file.
Here is my code:
import java.util.*;
import java.io.*;
import java.io.Serializable;
public class Deserialization{
public static void main(String [] args) {
Student st1 = null;
Student st2 = null;
Student st3 = null;
String opcion=null;
Scanner lol=new Scanner (System.in);
try {
FileInputStream fileIn = new FileInputStream("input.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
st1 = (Student) in.readObject();
st2 = (Student) in.readObject();
st3 = (Student) in.readObject();
do{ //HERE IS WHEREI WANT TO ASK MY USER AND REALIZE IT
System.out.println("Want to change?\n");
opcion=lol.next();
lol.nextLine();
}while(opcion.equals("y")||opcion.equals("Y"));
in.close();
fileIn.close();
} catch (IOException i) {
i.printStackTrace();
return;
} catch (ClassNotFoundException c) {
System.out.println("Class not found");
c.printStackTrace();
return;
}
System.out.println("Deserialized File...");
System.out.println("Student 1");
System.out.println("Name: " +st1.name);
System.out.println("ID: " +st1.id);
System.out.println("Average: " +st1.average);
System.out.println("Student 2");
System.out.println("Name: " +st2.name);
System.out.println("ID: " +st2.id);
System.out.println("Average: " +st2.average);
System.out.println("Student 3");
System.out.println("Name: " +st3.name);
System.out.println("ID: " +st3.id);
System.out.println("Average: " +st3.average);
}
}
lization part
Suppose you have a Student class like -
public class Student {
private String Name;
private int ID;
private int Average;
/**
* #return the name
*/
public String getName() {
return Name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
Name = name;
}
/**
* #return the iD
*/
public int getID() {
return ID;
}
/**
* #param iD the iD to set
*/
public void setID(int iD) {
ID = iD;
}
/**
* #return the average
*/
public int getAverage() {
return Average;
}
/**
* #param average the average to set
*/
public void setAverage(int average) {
Average = average;
}
}
After deserialization you will get an Object read from a file, now you want to modify Student object.
st1 = (Student) in.readObject();
st2 = (Student) in.readObject();
st3 = (Student) in.readObject();
Here st1,st2, and st3 Student object you have.
You can modify st1 name by calling setter method of Student Object.
For example if you want to modify student name you just need to call
st1.setName("modifyName");
After modify you can write st1 modified object in file in usual manner.

Void-type not allowed here error [duplicate]

This question already has answers here:
What causes "'void' type not allowed here" error
(7 answers)
Closed 10 months ago.
I am trying to add these data I have read from a file into my map. My map is a treemap TreeMap<String, Student>, where Student in another class. I am trying to use the code map.put(formatSNumber, student.setCourses(courses)); to add the read file elements to my map, but I keep encountering that void type not allowed here error.
sNumber = Integer.parseInt(Breader.readLine());
formatSNumber = String.format("%03d", sNumber);
hours = Integer.parseInt(Breader.readLine());
grade = Double.parseDouble(Breader.readLine());
Student student = map.get(formatSNumber);
Course course = new Course(hours, grade);
List<Course> courses = student.getCourses();
courses.add(course);
map.put(formatSNumber, student.setCourses(courses));
end = Breader.ready();
Here is my full code:
import java.io.*;
import java.util.Scanner;
import java.util.TreeMap;
import java.util.Iterator;
import java.util.List;
public class FinalProgram {
public static void main(String[] args) throws IOException {
String nameFile = " ";
String classFile = " ";
TreeMap<String, Student> map = new TreeMap<>();
Scanner input = new Scanner(System.in);
try {
System.out.print("Enter the Name file(c:filename.txt): ");
nameFile = input.nextLine();
} catch(IllegalArgumentException e) {
System.out.printf("Invalid input. Please enter"
+ " filename in the form of "
+ "c:filename.txt\n", e.getMessage());
}
nameReader(nameFile, map);
try {
System.out.print("Enter the Class file(c:filename.txt): ");
classFile = input.nextLine();
} catch(IllegalArgumentException e) {
System.out.printf("Invalid input. Please enter"
+ " filename in the form of "
+ "c:filename.txt\n", e.getMessage());
}
classReader(classFile, map);
}
private static void nameReader(String file, TreeMap<String, Student> map)
throws IOException {
String nameFile = file;
int sNumber = 0;
String formatSNumber = " ";
String sName = " ";
//Instantiate FileReader and BufferedReader
FileReader freader = new FileReader(nameFile);
BufferedReader Breader = new BufferedReader(freader);
boolean end = Breader.ready();
do {
sNumber = Integer.parseInt(Breader.readLine());
formatSNumber = String.format("%03d", sNumber);
sName = Breader.readLine();
Student student = new Student(sName);
map.put(formatSNumber, student);
end = Breader.ready();
} while(end);
Iterator<String> keySetIterator = map.keySet().iterator();
while(keySetIterator.hasNext()) {
String key = keySetIterator.next();
System.out.println("key: " + key + " value: " + map.get(key).getName());
}
}
private static void classReader(String file, TreeMap<String, Student> map)
throws IOException {
String classFile = file;
int sNumber = 0;
String formatSNumber = " ";
int hours = 0;
double grade = 0.0;
double points = grade * hours;
double GPA = points / hours;
//Instantiate FileReader and BufferedReader
FileReader freader = new FileReader(classFile);
BufferedReader Breader = new BufferedReader(freader);
boolean end = Breader.ready();
do {
sNumber = Integer.parseInt(Breader.readLine());
formatSNumber = String.format("%03d", sNumber);
hours = Integer.parseInt(Breader.readLine());
grade = Double.parseDouble(Breader.readLine());
Student student = map.get(formatSNumber);
Course course = new Course(hours, grade);
List<Course> courses = student.getCourses();
courses.add(course);
map.put(formatSNumber, student.setCourses(courses));
end = Breader.ready();
} while(end);
points = grade * hours;
GPA = points / hours;
}
}
Student class:
import java.util.ArrayList;
import java.util.List;
public class Student {
private String name = " ";
private List<Course> courses = new ArrayList<>();
public Student(String name) {
this.name = name;
}
public Student(String name, List courses) {
this.name = name;
this.courses = courses;
}
public List getCourses() {
return courses;
}
public void setCourses(List courses) {
this.courses = courses;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Course class:
public class Course {
private int hours = 0;
private double grade = 0.0;
public Course(int hours, double grade) {
this.hours = hours;
this.grade = grade;
}
public void setHours(int hours) {
this.hours = hours;
}
public int getHours() {
return hours;
}
public void setGrade(double grade) {
this.grade = grade;
}
public double getGrade() {
return grade;
}
}
The second argument in map.put(formatSNumber, student.setCourses(courses)) must be of type Student. student.setCourses(courses) is a setter method with return type void, i.e. no return. This does not match.
You must have something like map.put("someString", new Student("name")) for instance, or map.put("someString", student) where student is of type Student.
The idea of put is about putting something into that Map.
More precisely, you typically provide (non-null) key and a value objects.
You are using student.setCourses(courses) as argument for that "value" parameter that put() expects.
That argument is an expression. And the result of that expression would be the result of the method call.
That method is defined to not return anything (void that is).
Obviously nothing is not the same as something. And that is what the compiler tries to tell you.
Two solutions:
pass a Student object
change that method setCourses()
Like this:
Student setCourses(... {
....
return this;
}
( you better go for option 1; 2 is more of a dirty hack, bad practice in essence )

Categories