Java - Reading a Text File and Adding a Unique ID - java

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

Related

Searching a string in a text file and learning which line is it

I have a text file like down below:
jack; 488;22;98
kylie; 541;72;81
jenna; 995;66;17 .
.
The list is formatted as follows:
On every line, the first number after the name is the student's code and the numbers following it are scores.
I want to pass the student's code (as a String) as the input to the program and it should return the student's second score to me.
I have tried bufferedreader ,but I can just write all text files as output, but I can't search for the code and the other things.
Thanks
BufferedReader br = new BufferedReader(new FileReader("filePath"));
String contentLine = br.readLine();
while (contentLine != null) {
String[] result=contentLine.split(";");
String studentCode =result[1].trim();
// apply your logic for studentCode here
contentLine = br.readLine();
}
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
public class FilterCsv {
private class Student {
private String name;
private String code;
private String score;
private String score2;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getScore() {
return score;
}
public void setScore(String score) {
this.score = score;
}
public String getScore2() {
return score2;
}
public void setScore2(String score2) {
this.score2 = score2;
}
#Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", code='" + code + '\'' +
", score='" + score + '\'' +
", score2='" + score2 + '\'' +
'}';
}
}
private Function<String, Student> mapToItem = (line) -> {
System.out.println(line);
String[] p = line.split(";");
Student student = new Student();
student.setName(p[0]);
if (p[1] != null && p[1].trim().length() > 0) {
student.setCode(p[1]);
}
if (p[2] != null && p[2].trim().length() > 0) {
student.setScore(p[2]);
}
if (p[3] != null && p[3].trim().length() > 0) {
student.setScore2(p[3]);
}
return student;
};
private List<Student> processInputFile(String inputFilePath, String name) {
List<Student> inputList = new ArrayList<>();
try {
File inputF = new File(inputFilePath);
InputStream inputFS = new FileInputStream(inputF);
BufferedReader br = new BufferedReader(new InputStreamReader(inputFS));
// skip the header of the csv
inputList = br.lines().map(mapToItem).collect(Collectors.toList());
br.close();
String secondScore = inputList
.stream()
.peek(System.out::println)
.filter((s -> s.getName().equals(name)))
.findFirst()
.get().getScore2();
System.out.println("Score 2 for " + name + " is: " + secondScore);
} catch (IOException e) {
System.out.println(e);
}
return inputList;
}
public static void main(String[] args) {
new FilterCsv().processInputFile("your filepath, "studentsName");
}
}
add some error checking and stuff...
Cheers

How to read values from a text file into hashmap in Java?

I have created class Patient (pojo), where I have declared variables.
I have added getter and setter methods, as well as a constructor:
public class Patient {
private String patientName;
private String phoneNumber;
private int age;
//generate getter and setter method
public String getPatientName() {
return patientName;
}
public void setPatientName(String patientName) {
this.patientName = patientName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
//generate constructor
public Patient(String patientName, String phoneNumber, int age) {
this.patientName = patientName;
this.phoneNumber = phoneNumber;
this.age = age;
}
}
I have created an interface PatientDetails and implemented the methods in the Hospital class.
public interface PatientDetails {
public void addpatient();
public void refreshPatient()throws IOException;
}
Here is how the methods are implemented:
public class Hospital implements PatientDetails {`
Scanner scan = new Scanner(System.in);
int token = 0;
String name, mobileNumber;
static HashMap<Integer, Patient> map = new HashMap<Integer, Patient>();
File file = new File("E:\\Patient\\pt.txt");
int age;
public void addpatient() {
BufferedWriter bufferedWriter = null;
FileWriter fileWriter = null;
try {
// true = append file
// write a data in a file
fileWriter = new FileWriter(file, true);
bufferedWriter = new BufferedWriter(fileWriter);
System.out.println("Enter the name");
scan.nextLine();
name = scan.nextLine();
System.out.println("Enter Mobile number must be 10 digit");
mobileNumber = scan.nextLine();
System.out.println("Enter the age");
age = scan.nextInt();
bufferedWriter.write("TokenNumber:" + token + "," + "PatientName:" + name + ",PhoneNumber:" + mobileNumber
+ ",Age :" + age + ";");
// for nextline
bufferedWriter.newLine();
// close file
bufferedWriter.close();
fileWriter.close();
System.out.println("yours Appoint cofirmed....\nPatient Name: " + name + "\nMobile number: " + mobileNumber
+ "\nToken number is: " + token + "\nAge is:" + age);
token++;
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Something went wrong");
e.printStackTrace();
}
}
#Override
public void refreshPatient() throws IOException {
Patient patient=new Patient(mobileNumber, mobileNumber, age);
String filePath = file.getPath();
System.out.println("refreshed successfully");
String line;
BufferedReader reader = new BufferedReader(new FileReader(filePath));
map=new HashMap<>();
while ((line = reader.readLine()) != null) {
String[] parts = line.split(":", 2);
if (parts.length >= 2) {
String key = parts[0];
String value = parts[1];
//map.put(Integer.parseInt(key), value);
} else {
System.out.println("ignoring line: " + line);
}
}
System.out.println(map);
reader.close();
}`)
I have added the patient name, age, and mobile number into the patient.txt file.
When I call the refresh method all the values should come to the map, but I am not getting the Patient class values into the map.
How to fix that?
you should split with , before :.

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 )

Unhandled ClassNotFound Exception when reading object

So, I'm trying to read in an Object from a file, and I can't figure out why I'm getting this exception, or how to fix it. Maybe you guys can help me out? I've tried messing around with the way I read the object, but can't get it quite right. Here is my code I'm getting the error on the line that reads listOfEmployeesIn[i] = (Employee) objIn.readObject();:
import java.util.Random;
import java.io.*;
public class ProjectFive{
public static void main(String[] args) throws IOException{
Random rn = new Random();
RandomAccessFile file = new RandomAccessFile("employees.txt", "rw");
FileOutputStream fileOut = new FileOutputStream("employees.txt");
ObjectOutputStream objOut = new ObjectOutputStream(fileOut);
FileInputStream fileIn = new FileInputStream("employees.txt");
ObjectInputStream objIn = new ObjectInputStream(fileIn);
Object x;
long SSN;
float salary;
int age;
float maxSalary = 200000;
float minSalary = 20000;
long SSNRange = 1000000000;
String[] names = {"Matty Villa"};
Employee[] listOfEmployeesOut = new Employee[20];
Employee[] listOfEmployeesIn = new Employee[20];
for(int i=0;i<listOfEmployeesOut.length;i++){
SSN = (long)(rn.nextDouble()*SSNRange);
salary = rn.nextFloat()*(maxSalary - minSalary)+minSalary;
age = rn.nextInt(57)+18;
listOfEmployeesOut[i] = new Employee(SSN, names[i], salary, age);
}
for(int i = 0;i<listOfEmployeesOut.length;i++){
objOut.writeObject(listOfEmployeesOut[i]);
}
for(int i = 0;i<listOfEmployeesIn.length;i++){
listOfEmployeesIn[i] = (Employee) objIn.readObject();
}
file.close();
fileOut.close();
objOut.close();
fileIn.close();
objIn.close();
}
}
class Employee implements Serializable{
public long socialSecurityNumber;
public String fullName;
public float salary;
public int age;
public Employee(long socialSecurityNumber, String fullName, float salary, int age){
this.socialSecurityNumber = socialSecurityNumber;
if(fullName.length() != 50){
fullName = resizeString(fullName);
}
this.fullName = fullName;
this.salary = salary;
this.age = age;
}
private String resizeString(String s){
if(s.length() < 50){
for(int i = s.length(); i<=50; i++){
s += ' ';
}
}else{
s = s.substring(0,50);
}
return s;
}
public String toString(){
String out = "Name: " + fullName + "\nSalary: " + salary + "\nSocial: " + socialSecurityNumber
+ "\nAge: " + age;
return out;
}
}
As per JAVA API for ObjectInputStream, the method readObject throws checked exceptions - IOException, ClassNotFoundException
So either throw this exception from main method:
public static void main(String[] args) throws IOException, ClassNotFoundException
or handle it using try/catch blocks:
try {
listOfEmployeesIn[i] = (Employee) objIn.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}

Why am I getting an Array Index Out Of Bounds Exception error when parsing lines?

In netbeans I got an Array Index Out Of Bounds Exception error in my code at line 35 in the MyProj03 class from line 55 in the Person class. I am not sure why I am getting this error.
My code:
import java.util.Scanner;
import java.io.*;
import birch.Person.*;
public class MyProj03 {
public static void main(String[] args) throws IOException {
// check for file existence
File file = new File("p3text.txt");
if (file.exists())
{
// read each record into a String
StringBuilder fileContents = new StringBuilder((int)file.length());
Scanner scanner = new Scanner("p3text.txt");
String lineSeparator = System.getProperty("line.separator");
try {
while(scanner.hasNextLine()) {
fileContents.append(scanner.nextLine() + lineSeparator);
Person one = new Person();
one.parseCommaDelim(fileContents.toString());
}
} finally
{
scanner.close();
}
}
else if (!file.exists())
{
System.out.println("The file p3text.txt is not found.");
System.exit(2);
}
}
}
more code:
public class Person {
//make instance fields for name, city, age, and SiblingCount
public String name;
public int age;
public String city;
public int sibCount;
public Person()
{
name = "";
age = 0;
city = "";
sibCount = 0;
}
// public access methods (getters)
public String getPerson() {
return this.name;
}
public int getAge() {
return this.age;
}
public String getCity() {
return this.city;
}
public int getSibCount() {
return this.sibCount;
}
// make a toString method
public String toString()
{
String str = "person: " + name + "age: " + age + "city: " + city;
return str;
}
// make a method called parseCommaDelim
public Person parseCommaDelim(String s) {
String[] tokens = s.split(",");
Person instance = new Person();
instance.name = tokens[0];
instance.age = Integer.parseInt(tokens[1]); //ArrayIndexOutOfBoundsException error
instance.city = tokens[2];
instance.sibCount = Integer.parseInt(tokens[3]);
return instance;
}
public int getIndex(Arrays list[], String key)
{
for (int index = 0; index< list.length; index++)
{
if ( list[index].equals(key) )
return index;
}
return -1;
}
}
My text file
Rhonda, 20 , San Diego , 1
Kaitlin, 24 , Provo , 4
Bret, 24 , Columbia , 4
Chris, 28 , Escondido , 2
Dylan, 21, Portland, 3
You can scan file's content line by line and process with this code:
public class MyProj03 {
public static void main(String[] args) throws IOException {
File file = new File("p3text.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
Person one = new Person();
one.parseCommaDelim(line);
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
also I recommend you to change the fragment codes :
Person instance = new Person();
instance.name = tokens[0];
instance.age = Integer.parseInt(tokens[1]); //ArrayIndexOutOfBoundsException error
instance.city = tokens[2];
instance.sibCount = Integer.parseInt(tokens[3]);
to this:
Person instance = new Person();
instance.name = tokens[0];
instance.age = Integer.parseInt(tokens[1].trim()); //ArrayIndexOutOfBoundsException error
instance.city = tokens[2];
instance.sibCount = Integer.parseInt(tokens[3].trim());
You should replace
Person one = new Person();
one.parseCommaDelim(lineSeparator);
with
Person one = new Person();
one.parseCommaDelim(fileContents.toString());
as your current implementation tries to parse the , itself, not the string your read.

Categories