JAVA, Read from a text file, print out info from the array - java

very new to Java and I have a question
I was given an text file, and asked to find the employee who earn the most, and print out their info (fName, Lname, ID)
the text file was like so:
Date of birth fName lName wage hr work emp ID
12/03/1929 Detzk Fyshe 37 49 07036310484
04/17/1930 Cauus Walden 38 52 63612537553
07/12/1930 Barth Harling 43 72 42101524036
07/16/1930 Bartl Barnhill 43 62 48621748867
I manage to find the max wage. But have no idea how to print out the info
Here my code so far:
public static void main(String[] args) {
File inFile = new File ("dataSet.txt");
ArrayList <String> inData = new ArrayList <String>();
String strline;
try
{
FileInputStream fstream = new FileInputStream(inFile);
BufferedReader br = new BufferedReader (new InputStreamReader (fstream));
while ((strline = br.readLine()) != null)
{
strline = strline.trim();
if ((strline.length()!=0)) inData.add(strline);
}
} catch (Exception e) {
System.err.println("Error CANNOT FIND FILE!");
}
// Max wage finder *start*
int maxWage=0;
for (int i=0; i<inData.size(); i++){
String [] word = inData.get(i).split(" ");
int wage=Integer.parseInt (word[3]);
int hrWork=Integer.parseInt (word[4]);
int earn = wage*hrWork;
if (earn>maxWage){
maxWage=earn;
}
}
System.out.println("Max Wage in $:"+maxWage);
//max wage finder *end*

If you're reading in employee data, then an object-oriented solution to the problem is to create an Employee class with strongly typed (dates as Dates, and integers as ints) attributes that model the contents of the file.
In addition to the instance variables that would store the actual data of each Employee, you might want to override the toString() method in the class so that the employee information can be easily output, for example to System.out. Also, you would need a getter for the "total salary" of an employee (which you calculate with wage * hrWork) so that the salaries of two employees can be compared externally, e.g. by a Comparator.
All in all, the code could look like this for the relevant parts:
private static final DateFormat FORMATTER = new SimpleDateFormat("MM/dd/yyyy");
...
List<Employee> employees = new ArrayList<Employee>();
...
// within the loop that reads the file:
String[] columns = strline.split(" ");
employees.add(new Employee(
FORMATTER.parse(columns[0]), // DOB,
columns[1], // first name
columns[2], // last name
Integer.parseInt(columns[3]), // wage
Integer.parseInt(columns[4]), // hr
columns[5]) // employee id
);
...
// after all lines have been read, output the employee with largest wage
Employee earnsMost = Collections.max(employees, new Comparator<Employee>() {
#Override
public int compare(Employee e1, Employee e2) {
return e1.getTotalSalary() - e2.getTotalSalary();
}
});
System.out.println(earnsMost + " earns most.");

Related

asking about non-primitives arraylist

I have created ArrayList. How can i use this list to get method or attribute from the class. I tried but i could not reach any solution.
I tried to get into element in array list and get some attributes but i can't.
public static void printOptions() {
System.out.println("Welcome to our university!");
System.out.println("Operations:");
System.out.println("1- College");System.out.println("a) Number of Departments");System.out.println("b) Number of Courses");System.out.println("c) Number of Professors");System.out.println("d) Number of Students");System.out.println("e) Report");
System.out.println("2- Department");System.out.println("a) New");System.out.println("b) Number of Courses");System.out.println("c) Number of Students");System.out.println("d) Is Full");System.out.println("e) Enroll");System.out.println("f) Report");
System.out.println("3- Course");System.out.println("a) New");System.out.println("b) Number of Students");System.out.println("c) Assign");System.out.println("d) Is assigned");System.out.println("e) Professor Name");System.out.println("f) Is Full");System.out.println("g) Enroll");System.out.println("h) Report");
System.out.println("4- Professor");System.out.println("a) New");System.out.println("b) Display Salary");System.out.println("c) Get Raise");System.out.println("d) Report");
System.out.println("5- Student");System.out.println("a) New");System.out.println("b) Report");
System.out.println("6- Quit");
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
printOptions() ;
List<Department> departmentList;departmentList = new ArrayList<>();
List<Course> courseList ;courseList = new ArrayList<>();
List<Professor> proffList = new ArrayList<>() ;
List<Student> studentList;studentList = new ArrayList<>() ;
Scanner in = new Scanner(System.in) ;
int d = 0 , c = 0 , p = 0 , s=0 ;
College AinShams = new College() ;
while (true){
String option = in.nextLine() ;
if(!"6".equals(option)) {
if ("2a".equals(option)) { // Define new department
System.out.println("Department Name:");
String depName = in.nextLine() ;
System.out.println("Department Description:");
String depDescripe = in.nextLine() ;
System.out.println("Department Max Students:");
int max_num = in.nextInt() ;
in.nextLine() ;
Department Department_Name = new Department(depName, depDescripe, max_num);
// departmentList.add(Department_Name);
departmentList.add(d, Department_Name);
d++ ;
AinShams.setDepart(departmentList);
}
else if ("4a".equalsIgnoreCase(option)) {//new proff
System.out.println("Professor Firstname:");
String firstName = in.nextLine() ;
System.out.println("Professor Lastname:");
String lastName = in.nextLine();
System.out.println("Professor telephone:");
String telephone = in.nextLine();
System.out.println("Professor address:");
String address = in.nextLine();
System.out.println("Professor salary:");
double salary = in.nextDouble() ;
Professor proff = new Professor(firstName, lastName, telephone, address, salary);
proffList.add(p,proff) ;
p++ ;
AinShams.setProf(proffList);
}
else if ("2e".equalsIgnoreCase(option)) {//add student in department
System.out.println("Department:");
String dep= in.nextLine() ;
System.out.println("Student:");
String stu= in.nextLine();
// System.out.println(AinShams.getDepart());
AinShams.getDepart().
/*for (int i = 0; i < AinShams.getDepart().size(); i++) {
}*/
}
System.out.println("============");
System.out.println("Enter Operation");
System.out.println("============");
}else {break ;}
}
}
}
In condition (2e), I need to get methods and attributes in class which I assigned in array List
AinShams.getDepart() is referring to an object which you defined as data type College:
College AinShams = new College();
The rest of the College code is not in this fragment so I cannot tell whether the .getDepart() method exists. Either way, the College is not an ArrayList.
If you want to reach the methods and fields of objects inside an ArrayList something like the following would work. As an example I take the ArrayList called departmentlist, and use the get() method to return the 0th element from that list. Assuming the 0th element of that class is an object of type Department, the .name asks for the name field (again, assuming this name variable exists in the Department class). The .getName() would be a better way to get the name value but requires you coding this method in the Department class.
departmentlist.get(0).name
departmentlist.get(0).getName()
By the way, consider reducing some of the "System.out.println()" clutter in the top of your code by formatting your output with the "\n" new line key. Try these two examples using 1 system.out.println call to print two lines of text:
System.out.println("Welcome to our university!" + "\n" + "Operations:");
System.out.println("Welcome to our university! \nOperations:");
You want to add a new student to a department. Your College class has other attributes like list of departments, professors, etc.
Approach:
You can get the Department object from the array list, by the department name (property) passed by the user in case-2e. Then use that object to insert new student to its student's list.
Code:
Your code can be something like below (Pardon any compilation error as I haven't used any IDE. Follow the approach):
String dept = in.nextLine();
Department department = AinShams.getDepart().stream().filter(department -> department.getName().contentEquals(dept)).limit(1);
department.getStudentList().add(new Student());
Follow the link for non-stream version:
How to find an object in an ArrayList by property
OR Use the following method:
Department findDepartment(List<Department> deptList, String dept) {
for(Department department : deptList) {
if(department.getName().equals(dept)) {
return department;
}
}
return null;
}

Is there a way loop through 2 arrays and print the element of array 1 if it contains the substring of any element from array 2?

The problem I am trying to solve is how to read lines from a text file and add it to an array. Then sort each element from this new array by the date that is also in each element. I will explain so its easier to understand but will explain what I am doing.
My text file (First column is name, second is Date of birth and last is the date the person died):
sarah jones,1966-12-02,2018-12-04
matt smith,1983-02-03,2020-03-02
john smith,1967-03-04,2017-04-04
I want to sort this file and output it to another file (testing by printing to console at the moment) by sorting it by the date the person died. A way I thought of doing this is to read each line and pass it to an array. Then read each element within the array, split it and then save the date the person died to another array. Then sort the array that has the death dates, loop through both arrays by seeing if the first element of the death date array matches the first element of the first line in the text file, if so then write it to another file. If not then go to the next line.
For example
BufferedReader reader = new BufferedReader(new FileReader("input_text.txt"));
PrintWriter outputStream = new PrintWriter(new FileWriter("output.txt",true));
ArrayList<String> lines = new ArrayList<String>();
ArrayList<String> substr_date = new ArrayList<String>();
String currentline = reader.readLine();
while(currentline !=null){
String a_line[] = currentline.split(",");
substr_date.add(a_line[2])
lines.add(currentline);
currentline = reader.readLine();
}
Collections.sort(substr_date);
for(String date : substr_date){
for(String line : lines){
if(line.contains(date)){
System.out.println(line);
}
}
}
I expect the output to be:
john smith,1967-03-04,2017-04-04
sarah jones,1966-12-02,2018-12-04
matt smith,1983-02-03,2020-03-02
The results are initially in order but then some lines are repeated multiple times and then the whole text file in repeated to the console and becomes a mess. I am not sure how to go about doing this. I am new to java and not sure if I asked this question properly either so if you need any more info please ask.
I would create class for objects which you can insert into a list and then define a comparator on this class which you can use to sort.
Here is an example of the class you could define:
static class DeceasedPerson {
String name;
LocalDate birthDate;
LocalDate deathDate;
DeceasedPerson(String name, LocalDate birthDate, LocalDate deathDate) {
this.name = name;
this.birthDate = birthDate;
this.deathDate = deathDate;
}
#Override
public String toString() {
return name + ", " + birthDate + ", " + deathDate;
}
}
Then you could simply load objects based on this class into a list which you sort using a comparator. Here is some sample code you can run with the class defined above:
public static void main(String[] args) {
String input =
"matt smith,1983-02-03,2020-03-02\n" +
"sarah jones,1966-12-02,2018-12-04\n" +
"john smith,1967-03-04,2017-04-04\n";
List<DeceasedPerson> deceasedPersonList = new ArrayList<>();
try (Scanner scanner = new Scanner(input)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] array = line.split(",");
DeceasedPerson deceasedPerson = new DeceasedPerson(array[0],
LocalDate.parse(array[1]), LocalDate.parse(array[2]));
deceasedPersonList.add(deceasedPerson);
}
}
deceasedPersonList.sort(Comparator.comparing(o -> o.deathDate));
deceasedPersonList.forEach(System.out::println);
}
If you run the code above using the DeceasedPerson class you should see on the console the following output:
john smith, 1967-03-04, 2017-04-04
sarah jones, 1966-12-02, 2018-12-04
matt smith, 1983-02-03, 2020-03-02
You could actually also use a TreeSet instead of a List in the main method above and achieve the same results. Here is a move concise alternative:
public static void main(String[] args) {
String input =
"matt smith,1983-02-03,2020-03-02\n" +
"sarah jones,1966-12-02,2018-12-04\n" +
"john smith,1967-03-04,2017-04-04\n";
Set<DeceasedPerson> deceasedPersonList = new TreeSet<>(Comparator.comparing(o -> o.deathDate));
try (Scanner scanner = new Scanner(input)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] array = line.split(",");
DeceasedPerson deceasedPerson = new DeceasedPerson(array[0],
LocalDate.parse(array[1]), LocalDate.parse(array[2]));
deceasedPersonList.add(deceasedPerson);
}
}
deceasedPersonList.forEach(System.out::println);
}
The way you are doing is a long shot. You can do this in much simpler way. You could pass a comparator to the Collections.sort() method like this.
Collections.sort(substr_date, new Comparator<String>{
#Override
public int compare(String str1, String str2){
String dd1 = str1.split(",")[2];
String dd2 = str2.split(",")[2];
return dd1.compareTo(dd2);
}
});
Comparing dates like this, though, is not a good approach. You should convert the date string to LocalDateTime and then use isBefore() or isAfter() to compare them. For ex,
public int compare(String str1, String str2){
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd")
LocalDateTime d1 = LocalDateTime.parse(str1.split(",")[2],format);
LocalDateTime d2 = LocalDateTime.parse(str2.split(",")[2],format);
return d1.isBefore(d2)?-1:(d1.isAfter(d2)?1:0);
}

JAVA Array Index Problems

I am not experienced wit Arrays and I am getting this error in the debug console:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1
at com.company.SortTextFile.main(SortTextFile.java:28)
I've been looking in internet for how other people handle this included here in StackOverflow but I can't seem to understand why is it happening. I am trying to have this program get the input from a text file of multiple columns with 20 lines like this:
Eduardo 15 3.9 30000
And then using collection.sort to sort it using its id.
I am aware the arrays are 0-index however I don't know if I would need to specify the array size.
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import static java.lang.Double.*;
public class SortTextFile {
public static void main(String[] args) throws IOException {
// Creating BufferedReader object to read the input text file
BufferedReader reader = new BufferedReader(new FileReader(
"C:\\Users\\miche\\OneDrive\\Documentos\\University\\Algorithms\\Project\\StudentData.txt"));
// Creating ArrayList to hold Student objects
var studentRecords = new ArrayList<Student>();
// Reading Student records one by one
String currentLine = reader.readLine();
while (currentLine != null) {
String[] studentDetail = currentLine.split("\\s+");
String name = studentDetail[0];
int age = Integer.valueOf(studentDetail[1]);
double GPA = valueOf(studentDetail[2]);
int id = Integer.valueOf(studentDetail[3]);
// Creating Student object for every student record and adding it to
// ArrayList
studentRecords.add(new Student(name, age, GPA, id));
currentLine = reader.readLine();
}
// Sorting ArrayList studentRecords based on marks
Collections.sort(studentRecords, new idCompare());
// Creating BufferedWriter object to write into output text file
BufferedWriter writer = new BufferedWriter(new FileWriter(
"C:\\C:\\Users\\miche\\OneDrive\\Documentos\\University\\Algorithms\\Project\\output.txt"));
// Writing every studentRecords into output text file
for (Student student : studentRecords) {
writer.write(student.name);
writer.write(" " + student.age);
writer.write(" " + student.GPA);
writer.write(" " + student.id);
writer.newLine();
}
// Closing the resources
reader.close();
writer.close();
}
}
I made a Student class to compare the IDs.
public class Student extends SortTextFile {
String name;
int id;
int age;
double GPA;
public Student(String name, int id, double age, double GPA) {
this.name = name;
this.id = id;
this.age = (int) age;
this.GPA = GPA;
}
}
//idCompare Class to compare the marks
class idCompare implements Comparator<Student> {
#Override
public int compare(Student s1, Student s2) {
return s2.id - s1.id;}
}
Edit 1:
The text file just follows a format of Name/Age/GPA/ID:
Chipaldo 25 3.5 29000
Eduardo 15 3.9 30000
Ricardo 23 3.8 18000
Anthony 24 3.9 19000
Lombardo 29 2.0 22000
Romina 28 2.1 23000
Alex 25 3.1 13000
Sofia 21 2.2 24000
Vexler 24 2.2 25000
Albert 19 3.2 14000
John 24 3.0 15000
Melchor 14 2.9 16000
Bernardo 21 4.0 17000
Diego 19 2.1 26000
Miguelangel 25 2.0 27000
Edit 3: I managed to printout the Output in a new file. It sorted it based on age and not ID for some reason. Thank you for your help. I am going to try implement and Binary Insertion Sort to this program instead of doing Collection.sort Thanks.
If possible please be as detailed as possible with any suggestion. English is not my main language & I am slow at this. Thank you in advance
The message simply means that you have an array that only has 1 element in it and you are trying to access array element 2. This is one of those weird things in computer science (and Java as a language) because we start counting from zero rather than one, i.e. the first element in an array is indexed as studentDetail[0] and the second as studentDetail[1]. This is why you see the rather confusing "Index 1 out of bounds for length 1". The array being returned by currentLine.split(" ") only contains one string, not four, as you are expecting. You need to debug the code to find out why this is happening (from what you've provided this is not possible for someone else to answer).
your array seems to only have one entry. check if there is a problem with your string.split(" ")?
Use currentLine.split("\\s+"); This means that there may be one or more spaces or tabs or newlines between fields.
What you did will work correctly if and only if the fields are separated by one single space.
For debugging purpose print the length of the array using System.out.println(studentDetail.length);
Try This. Your code you did not closed writer thats why nothing is to in the output file.
public static void main(String[] args) throws IOException {
//Creating BufferedReader object to read the input text file
BufferedReader reader = new BufferedReader(new FileReader("E:\\Projects\\JavaBasics\\src\\data.txt"));
//Creating ArrayList to hold Student objects
var studentRecords = new ArrayList<Student>();
//Reading Student records one by one
String currentLine = null;
while ((currentLine = reader.readLine()) != null) {
if (!currentLine.isEmpty()) {
System.out.println(currentLine);
String[] studentDetail = currentLine.split(" ");
String name = studentDetail[0];
int age = Integer.valueOf(studentDetail[1]);
double GPA = Double.valueOf(studentDetail[2]);
int id = Integer.valueOf(studentDetail[3]);
studentRecords.add(new Student(name, age, GPA, id));
}
}
//Sorting ArrayList studentRecords based on marks
Collections.sort(studentRecords, new IdCompare());
//Creating BufferedWriter object to write into output text file
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(new File("E:\\Projects\\JavaBasics\\src\\dataout.txt")));
//Writing every studentRecords into output text file
for (Student student : studentRecords) {
System.out.println("Sorted :: " + student.name);
writer.write(student.name);
writer.write(" " + student.age);
writer.write(" " + student.GPA);
writer.write(" " + student.id);
writer.newLine();
}
} finally {
writer.close();
}
}

Reading a special txt file in java

What I want to do is read a text file that has humans and animals. It will compile but has an error when I try to run it. I think I need a for loop to read the stringtokenizer to decipher between the human and animal in the txt file so far this is my driver class.
txt file:
Morely,Robert,123 Anywhere Street,15396,4,234.56,2
Bubba,Bulldog,58,4-15-2010,6-14-2011
Lucy,Bulldog,49,4-15-2010,6-14-2011
Wilder,John,457 Somewhere Road,78214,3,124.53,1
Ralph,Cat,12,01-16-2011,04-21-2012
Miller,John,639 Green Glenn Drive,96258,5,0.00,3
Major,Lab,105,07-10-2012,06-13-2013
King,Collie,58,06-14-2012,10-05-2012
Pippy,cat,10,04-25-2015,04-25-2015
Jones,Sam,34 Franklin Apt B,47196,1,32.09,1
Gunther,Swiss Mountain Dog,125,10-10-2013,10-10-2013
Smith,Jack,935 Garrison Blvd,67125,4,364.00,4
Perry,Parrot,5,NA,3-13-2014
Jake,German Shepherd,86,11-14-2013,11-14-2013
Sweetie,tabby cat,15,12-15-2013,2-15-2015
Pete,boa,8,NA,3-15-2015
Source:
import java.util.Scanner;
import java.util.StringTokenizer;
import java.io.File;
import java.io.IOException;
/**
* This is my driver class that reads from a txt file to put into an array and uses the class refrences so it can use the menu and spit out
*
* #author ******
* #version 11/25/2015
*/
public class Driver
{
/**
* Constructor for objects of class Driver, what it does is read in the txt file gets the two class refrences and loops through to read through the whole file looking for string tokens to go to the next line
* and closes the file at the end also uses for loop to count number of string tokens to decipher between human and pets.
*/
public static void main(String[] args) throws IOException
{
Pet p;
Human h;
Scanner input;
char menu;
input = new Scanner(new File("clientdata.txt"));
int nBalance;
int id;
/**
* this while statement goes through each line looking for the string tokenizer ",". I want to count each "," to decipher between Human and Animal
*/
while(input.hasNext())
{
StringTokenizer st = new StringTokenizer(input.nextLine(), ",");
h = new Human();
h.setLastName(st.nextToken());
h.setFirstName(st.nextToken());
h.setAddress(st.nextToken());
h.setCiD(Integer.parseInt(st.nextToken()));
h.setVisits(Integer.parseInt(st.nextToken()));
h.setBalance(Double.parseDouble(st.nextToken()));
p = new Pet(st.nextToken(), st.nextToken(), Integer.parseInt(st.nextToken()), st.nextToken(), st.nextToken());
}
/**
* this is my seond while statement that loops the case switch statements and asks the user for client ID
*/
menu = 'Y';
while(menu == 'y' || menu == 'Y') {
System.out.print("\nChose one:\n A- client names and outstanding balance \n B- client's pets, name, type and date of last visit\n C-change the client's outstanding balance: ");
menu = input.next().charAt(0);
System.out.print("Enter client ID: ");
id = input.nextInt();
h = new Human();
if(id == h.getCiD())//if the id entered up top is equal to one of the id's in the txt file then it continues to the menu
{
p = new Pet();
switch(menu)
{ case 'A':
System.out.println("client name: " + h.getFirstName() + "outstanding balance: " + h.getBalance());
break;
case 'B':
System.out.println("pet's name: " + p.getName() + "type of pet: " + p.getTanimal() + "date of last visit: " + p.getLastVisit());
break;
case 'C':
System.out.println("what do you want to change the clients balances to?");
input.close();
}
}
else// if not then it goes to this If statement saying that the Client does not exist
{
System.out.println("Client does not exist.");
}
}
}
}
You have a number of issues you need to overcome...
For each line, you need to determine the type of data the line represents
You need some way to keep track of the data you've loaded (of the clients and their pets)
You need some way to associate each pet with it's owner
The first could be done in a number of ways, assuming we can change the data. You could make the first token meaningful (human, pet); you could use JSON or XML instead. But lets assume for the moment, you can't change the format.
The key difference between the two types of data is the number of tokens they contain, 7 for people, 5 for pets.
while (input.hasNext()) {
String text = input.nextLine();
String[] parts = text.split(",");
if (parts.length == 7) {
// Parse owner
} else if (parts.length == 5) {
// Parse pet
} // else invalid data
For the second problem you could use arrays, but you would need to know in advance the number of elements you will need, the number of people and for each person, the number of pets
Oddly enough, I just noticed that the last element is an int and seems to represent the number of pets!!
Morely,Robert,123 Anywhere Street,15396,4,234.56,2
------------^
But that doesn't help us for the owners.
For the owners, you could use a List of some kind and when ever you create a new Human, you would simply add them to the List, for example...
List<Human> humans = new ArrayList<>(25);
//...
if (parts.length == 7) {
// Parse the properties
human = new Human(...);
humans.add(human);
} else if (parts.length == 5) {
Thirdly, for the pets, each Pet should associated directly with the owner, for example:
Human human = null;
while (input.hasNext()) {
String text = input.nextLine();
String[] parts = text.split(",");
if (parts.length == 7) {
//...
} else if (parts.length == 5) {
if (human != null) {
// Parse pet properties
Pet pet = new Pet(name, type, age, date1, date2);
human.add(pet);
} else {
throw new NullPointerException("Found pet without human");
}
}
Okay, so all this does, is each time we create a Human, we keep a reference to the "current" or "last" owner created. For each "pet" line we parse, we add it to the owner.
Now, the Human class could use either a array or List to manage the pets, either will work, as we know the expected number of pets. You would then provide getters in the Human class to get a reference to the pets.
Because out-of-context code can be hard to read, this is an example of what you might be able to do...
Scanner input = new Scanner(new File("data.txt"));
List<Human> humans = new ArrayList<>(25);
Human human = null;
while (input.hasNext()) {
String text = input.nextLine();
String[] parts = text.split(",");
if (parts.length == 7) {
String firstName = parts[0];
String lastName = parts[1];
String address = parts[2];
int cid = Integer.parseInt(parts[3]);
int vists = Integer.parseInt(parts[4]);
double balance = Double.parseDouble(parts[5]);
int other = Integer.parseInt(parts[6]);
human = new Human(firstName, lastName, address, cid, vists, balance, other);
humans.add(human);
} else if (parts.length == 5) {
if (human != null) {
String name = parts[0];
String type = parts[1];
int age = Integer.parseInt(parts[2]);
String date1 = parts[3];
String date2 = parts[4];
Pet pet = new Pet(name, type, age, date1, date2);
human.add(pet);
} else {
throw new NullPointerException("Found pet without human");
}
}
}
What about using split() function instead of using StringTokenizer?
Say, You can change your first while loop like below:
while (input.hasNext()) {
// StringTokenizer st = new StringTokenizer(input.nextLine(), ",");
String[] tokens = input.nextLine().split(",");
if (tokens.length == 7) {
h = new Human();
h.setLastName(tokens[0]);
h.setFirstName(tokens[1]);
h.setAddress(tokens[2]);
h.setCiD(Integer.parseInt(tokens[3]));
h.setVisits(Integer.parseInt(tokens[4]));
h.setBalance(Double.parseDouble(tokens[5]));
} else {
p = new Pet(tokens[0], tokens[1], Integer.parseInt(tokens[2]), tokens[3], tokens[4]);
}
}
And for keeping track of which pet belongs to which human, you can append an arrayList of type Pet in Human class like below:
ArrayList<Pet> pets = new ArrayList<>();
And say you have another ArrayList of type Human named humans in the main function. So, you could append in if block like:
humans.add(h);
and in the else section, you could append in else block:
humans.get(humans.size()-1).pets.add(p);
You can try something like this -
Populate a map and then using that you can assign values according to your requirement.
public void differentiate(){
try {
Scanner scan=new Scanner(new BufferedReader(new FileReader("//your filepath")));
Map<String,List<String>> map=new HashMap<String, List<String>>();
while(scan.hasNextLine()){
List<String> petList=new ArrayList<String>();
String s=scan.nextLine();
String str[]=s.split(",");
String name=str[1]+" "+str[0];
int petCount=Integer.parseInt(str[str.length-1]);
for(int i=1;i<=petCount;i++){
String petString=scan.nextLine();
petList.add(petString);
}
map.put(name, petList);
}
Set<String> set=map.keySet();
for(String str:set){
System.out.println(str+" has "+map.get(str)+" pets");
}
}
catch (FileNotFoundException e) {
System.out.println(e.getMessage());
}
}

How to combine scanner and multimap?

I have two files and am trying to read each file line by line by using scanner. Also, I would like to combine these two file with the same Key(name) by using multimap in order to combine these two file into one. Here is the script I have so far. Can someone please give me the suggestion? Thank you.
001.csv contains:
David 188 Male doctor A
Jacob 190 Male CEO A+
Sam 175 Male Engineer A-
002.txt contains:
David 80kg US3000
Jacob 70kg US100000
Sam 65kg US80000
Source code:
public class same_test{
public static void main (String[] args) throws FileNotFoundException {
MultiMap multiMap = new MultiValueMap();
Scanner scanner1 = new Scanner(new File("001.csv"));
Scanner scanner2 = new Scanner(new File("002.txt"));
while (scanner1.hasNextLine()) {
String line = scanner1.nextLine();
String[] array = line.split("\t",2);
String TheName = array[0];
String score = array[1];
multiMap.put(TheName,score);
}
while (scanner2.hasNextLine()) {
String line2 = scanner2.nextLine();
String[] array2 = line2.split("\t",2);
String TheName2 = array2[0];
String rs = array2[1];
multiMap.put(TheName2,rs);
}
Set<String> keys = multiMap.keyset();
for (String key : keys){
System.out.println(key + "\t" + multiMap.get(key) );
}
}
}
Plz share what problem you facing or output you getting.
I run you code, it works for me.
I used MultiHashMap.
public static void main (String[] args) throws FileNotFoundException {
MultiMap multiMap = new MultiHashMap();
Scanner scanner1 = new Scanner(new File("/obp/f1.csv"));
Scanner scanner2 = new Scanner(new File("/obp/f2.csv"));
while (scanner1.hasNextLine()) {
String line = scanner1.nextLine();
String[] array = line.split("\\s",2);
String TheName = array[0];
String score = array[1];
multiMap.put(TheName,score);
}
while (scanner2.hasNextLine()) {
String line2 = scanner2.nextLine();
String[] array2 = line2.split("\\s",2);
String TheName2 = array2[0];
String rs = array2[1];
multiMap.put(TheName2,rs);
}
Set<String> keys = multiMap.keySet();
for (String key : keys){
System.out.println(key + "\t" + multiMap.get(key) );
}
}
output
David [188 Male doctor A , 80kg US3000 ]
Jacob [190 Male CEO A+ , 70kg US100000 ]
Sam [ 175 Male Engineer A- , 65kg US80000 ]
This answer is limited to the constraint that there is always a unique name like David. i.e. there will be only one David in the both the files.
Use
HashMap<String,Person> personMap = new HashMap<String,Person>();
Person Class will look like
class Person {
String name;
String sex;
int height;
int weight;
}
Note : Mark fields as private along with public setters and getters
Where Person is your POJO class containing all the relevant fields for a person. You will create a new Java POJO instance for every name during the scan of the first file and put an entry of this object mapped with the name. then, in the second scanner loop, you can get the Person object out of the map with the name from the second file (which matches actually) and set the remaining fields in it. On completion of the method, you will get all the details in the form of Person instances mapped with their names

Categories