Change the data from a deserialization code - java

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.

Related

Java - Reading a Text File and Adding a Unique ID

I am trying to learn Java and am really struggling on part of a problem that I have. I am being asked to write a method to read a text file where each line representing an instance of an object e.g. SalesPerson
The question is asking me to add an identifier id for every line that read in, the id is not present in the text file. I have id declared in my Sales Person class with a constructor and getter and setter methods, and have my method to read the text file below in another class. However it doesn't work and I am not sure where I am going wrong. Could someone give me a pointer..? I would be very grateful.,
public static Collection<SalesPerson> readSalesData() {
String pathname = CXU.FileChooser.getFilename();
File aFile = new File(pathname);
Scanner bufferedScanner = null;
Set<SalesPerson> salesSet = new HashSet<>();
try {
int id;
String name;
String productCode;
int sales;
int years;
Scanner lineScanner;
String currentLine;
bufferedScanner = new Scanner(new BufferedReader(new FileReader(aFile)));
while(bufferedScanner.hasNextLine()) {
currentLine = bufferedScanner.nextLine();
lineScanner = new Scanner(currentLine);
lineScanner.useDelimiter(",");
id = salesPerson.getId();
name = lineScanner.next(); //return the next token as a string
years = lineScanner.nextInt();
productCode = lineScanner.next(); // return the next token as a string
sales = lineScanner.nextInt(); // return the next token as a double
salesSet.add(new SalesPerson(id, name, years, productCode, sales));
}
}
catch (Exception anException) {
System.out.println("Error: " + anException);
}
finally {
try {
bufferedScanner.close();
}
catch (Exception anException) {
System.out.println("Error: " + anException);
}
}
return salesSet;
}
\\Constructor from Class SalesPerson
public SalesPerson(int aId, String aname, int aYears, String aProductCode, int aSales) {
super(); // optional
this.id = ++nextId;
this.name = aname;
this.years = aYears;
this.productCode = aProductCode;
this.sales = aSales;
}
Please check the following code I tried to make things little more simple:
package com.project;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
public class Temp {
public static void main(String[] args) {
Set<SalesPerson> salesPersons = (Set<SalesPerson>) readSalesData();
System.out.println(salesPersons.toString());
}
public static Collection<SalesPerson> readSalesData() {
Set<SalesPerson> salesPersons = new HashSet<>();
try {
File file = new File("D:/file.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
if (line.isEmpty())
break;
String[] rowData = line.split(";");
salesPersons.add(new SalesPerson(rowData[0].trim(), Integer.parseInt(rowData[1].trim()), rowData[2].trim(), Integer.parseInt(rowData[3].trim())));
}
fileReader.close();
} catch (Exception ex) {
System.out.println(ex);
}
return salesPersons;
}
}
package com.project;
public class SalesPerson {
// Static to keep reserve value with each new instance
private static int AUTO_ID = 1;
private int id;
private String name;
private int years;
private String productCode;
private int sales;
public SalesPerson() {
}
public SalesPerson(String name, int years, String productCode, int sales) {
this.id = AUTO_ID;
this.name = name;
this.years = years;
this.productCode = productCode;
this.sales = sales;
AUTO_ID++;
}
// Getters & Setters...
#Override
public String toString() {
return "ID: " + id + ", Name: " + name + ", Years: " + years + ", Product Code: " + productCode + ", Sales: " + sales + System.lineSeparator();
}
}
And this my data file:
FullName1 ; 20; p-code-001; 10
FullName2 ; 30; p-code-002; 14
FullName3 ; 18; p-code-012; 1040

How to read/writetwo HashMap objects to file in 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.

how can I read a text file, process it & write toString()

I'm having a number of issues with this:
1) Under which class would I want to put my Scanner, so that it assigns the proper variables? The task I am given says to "read data file into Students" in the Tester class
2) How can I make a readFile() method in the Students class?
3) How can I properly write toString() in both Student and Students classes?
import java.io.*;
import java.util.*;
public class Tester
{
public static void main(String args[]) throws IOException
{
//new Students object
Students theStudents = new Students();
//reads file from Students
theStudents.readFile();
// create new 'Output.txt' file to save program output
PrintWriter ot = new PrintWriter(new FileWriter("Output.txt"));
System.out.println(theStudents.toString());
ot.println(theStudents.toString());
ot.close();
}
}
import java.util.ArrayList;
import java.io.*;
import java.util.*;
import java.io.FileReader;
public class Students
{
// instance variables
private ArrayList<Student> students;
public Students()
{
//create arraylist for students
students = new ArrayList<>();
}
public void readFile() throws IOException
{
String name;
int age;
double gpa;
String line;
//Scanner to read file
try {
Scanner sc = new Scanner(new File("Students.txt"));
while (sc.hasNextLine()) {
name = sc.nextLine();
line = sc.nextLine();
age = Integer.parseInt(line);
line = sc.nextLine();
gpa = Double.parseDouble(line);
}
}
catch (FileNotFoundException e) {
System.out.println("Error");
}
}
public void add(Student s)
{
students.add(s);
}
public Students aboveAverage(double avgGPA)
{
Students aboveAverage = new Students();
for (int i = 0; i < students.size(); ++i) {
if (students.get(i).getGPA() > avgGPA)
aboveAverage.add(students.get(i));
}
return aboveAverage;
}
public String toString()
{
String out = "";
int count = 0;
for (Student student : students){
out += students.toString() + " ";
++count;
}
return out;
}
}
public class Student
{
private String name;
private int age;
private double gpa;
public Student(String studentName, int studentAge, double studentGPA)
{
name = studentName;
age = studentAge;
gpa = studentGPA;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public double getGPA()
{
return gpa;
}
public String toString()
{
return String.format("%10s", name) +
String.format("%5d", age) + String.format("%10.2f \n", gpa);
}
}
I'm not gonna give you the complete solution but here is a way to approach this problem.
You need readLine() instead of nextLine()
Once you read the values, you need to call the add() function with the Student Object to add it to your ArrayList.
Code Snippet:
try (Scanner sc = new Scanner(new File("Students.txt"))) {
while (sc.hasNextLine()) {
String name = sc.readLine();
int age = Integer.parseInt(sc.readLine());
double gpa = Double.parseDouble(sc.readLine());
/* Create A New Student Object & Add To List */
add(new Student(name, age, gpa));
}
} catch (FileNotFoundException e) {
System.out.println("Error");
}
Also, you need to #Override the toString() function.

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 )

i have trouble with printing an array after reading it in JAVA

i have problem with printing the array after reading it. After printing, the address of memory is printed, not value of the array. What can i do for that ?
public class MyClass
{
Student St = new Student();
Student[]Array1 = new Student[10];
void AddList()
{
Scanner Scan = new Scanner(System.in);
for (int i=0; i<Array1.length & i<ArrayF1.length; i++)
{
System.out.println("Enter Student NAME Number " + (i+1) + ":");
Array1[i] = new Student();
Array1[i].setName(Scan.next());
//System.out.println("Enter Student MARK Number " + (i+1) + ":");
//St.setMark(Scan.nextFloat());
}
}
this is my print method. The result of print is like this
(studentproject.Student#1a758cb)
void PrintList()
{
for (int i=0; i<Array1.length; i++)
{
System.out.println(Array1[i]);
}
}
this is my Student Class that i have all my setter and getter method on that ... So i have 3 Class how can i work with this 3 class and in one of them get the data and in another print the Mark data and in third class print the Student Name data ... how can i do that ... i do some code but i dont know is it correct or not ... thanks for your help ...
public class Student
{
private String Name;
private float Mark;
/**
* #return the Name
*/
public String getName() {
return Name;
}
/**
* #param Name the Name to set
*/
public void setName(String Name) {
this.Name = Name;
}
/**
* #return the Mark
*/
public float getMark() {
return Mark;
}
/**
* #param Mark the Mark to set
*/
public void setMark(float Mark) {
this.Mark = Mark;
}
}
Just override the toString() method in Student class, and return the appropriate string you want to get printed when you print an instance.
It may look like: -
#Override
public String toString() {
return "Name: " + studentName;
}
Currently, the default implementation of toString() method of Object class is invoked, and what you are seeing is the format returned from that method, which is of the form - Type#hashCode
Here I've added some stuff how toString() method can be override
public class Student {
private String name;
private int id;
float mark;
public Student() {
}
public Student(String name, int id) {
this.name = name;
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getMark() {
return mark;
}
public void setMark(float mark) {
this.mark = mark;
}
#Override
public String toString() {
return "Student[ID:" + id + ",Name:" + name + ",Mark:"+mark+"]";
}
public void printStudentInfo() {
// print all the details of student
}
public static void main(String[] args) {
Student[] students = new Student[10];
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < students.length; i++) {
System.out.println("Enter Student Name " + (i + 1) + ":");
String name = scanner.nextLine();
Student student = new Student(name, i + 1);
System.out.println("Enter Student MARK Number " + (i + 1) + ":");
float mark = scanner.nextFloat();
student.setMark(mark);
students[i]=student;
}
for(Student student:students) {
// by default toStirng method is called
System.out.println(student);
//or you can call like
//student.printStudentInfo();
}
}
}

Categories