My dad asked me to make a program for him that will randomly take a name, surname etc. from Excel (or CSV file) and assign employees to the work. Each person must be at work minimum once and maximum 4 times a month. Program output should look like this:
Day 1: John Smith, James Smith Day 2: Charlie Smith, Thomas Smith
And this is how my code looks like right now
public static void main(String[] args) {
String FileName = "excel.csv";
File f = new File(FileName);
String read = "";
Map<Integer, Surname>SurnameArray = new HashMap<Integer, Surname>();
try {
Scanner scanner = new Scanner(f);
while(scanner.hasNextLine()) {
read = scanner.nextLine();
String[] arraySplit = read.split(",");
int kod = Integer.parseInt(tablicaSplit[0]);
String rank = tablicaSplit[1];
String name = tablicaSplit[2];
String surname = tablicaSplit[3];
SurnameArray.put(kod, new Nazwiska(kod, rank, name, surname));
SurnameArray.get(kod).getAll();
}
} catch (FileNotFoundException e) {
System.out.println("No file!");
}
}
}
And the second class looks like this:
Class Surnames {
private int kod;
private String rank;
private String name;
private String surname;
public Surnames(int kod, String rank, String name, String surname) {
super();
this.kod = kod;
this.rank = rank;
this.name = name;
this.surname = surname;
}
public void getAll() {
System.out.println(rank + " " + name + " " + surname);
}
public int getKod() {
return kod;
}
public void setKod(int kod) {
this.kod = kod;
}
public String getRank() {
return rank;
}
public void setRank(String rank) {
this.rank = rank;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setNazwisko(String surname) {
this.surname = surname;
}
}
I'm stuck at this moment. I think that this code is more complicated than it should be. If someone could show me how can i make it or maybe there is simpler way to make something like this.
I would do it this way:
class Surnames{
private final HashSet<String> EMPLOYEES;
private ArrayList<String> positions;
Surnames(String csv){
HashSet<String> tempEMPLOYEES = new HashSet<>();
ArrayList<String> tempPositions = new ArrayList<>();
/*here the code for putting csv data ino an tempEMPLOYEE hashSet, or a static setter method doing this, as well for tempPositions, containing array list of positions remember to check
if the hashset's size is equal or lower than arrayList's*/
EMPLOYEES = tempEMPLOYEES;
positions = tempPosition;
}
public void printShift(){
for(int i = 0; i < EMPLOYEES.size(); i++){
System.out.println(positions.get(i) + "- " + EMPLOYEES.get(i));
}
}
}
Since hashSet gives different object position in the set every single run of the program, placing EMPLOYEES to positions will be random. I mentioned checking that HashSet EMPLOYEES should be less size than positions. I iterate on the hashset- every employee should get a position.
Related
I have 2 files a.txt and b.txt.
a.txt has 3 columns: id, name and month
e1,David,12
e2,Jane,24 e4,Peter,15 e3,John,25 ...
b.txt has 2 columns: id and baseSalary
e1,1200e2,1800e4,2400
...
I will read a.txt to an ArrayList.
public ArrayList<Employee> loadEmployee(String file) {
ArrayList<Employee> Emp = new ArrayList<Employee>();
ArrayList<String> employees = loadFile(file);
for (String emp : employees) {
String[] data = emp.split(",");
Emp.add(new Employee(data[0], data[1], Integer.parseInt(data[2])));
}
return Emp;
}
public class Employee{
private String id;
private String name;
private int month;
public Employee(String id, String name, int month){
this.id=id;
this.name=name;
this.month=month;
}
public double getSalary(int baseSalary){
return this.month*baseSalary;
}
public String toString(){
return this.id+"_"+this.name+"_"+this.month;
}
}
Now I want to get top 3 employee has highest salary.But you cannot create new class.
I don't know how to do. I'm new in java OPP. I think I will read b.txt to a hashmap, but hashmap cannot sort. So I cannot get top 3.
Anyone can help me?
Sorry if my English is not good.
Your loadEmployee method is a good start, but as you said you have to read the second file to get the base salary for each employee and compute their overall salary (I guess it's a total income).
You could define a second method, setEmployeeBaseSalary, which accepts the second file's name and the List of employees. Then, you basically read the second file in the same way you've done with the first one. For each id read, you perform a search through your List, gather the employee by its id and then set its base salary.
After updating your List of employees, you could use the collection stream to sort your list by salary, gather the first three results and then collect them into a new List.
public static ArrayList<Employee> loadEmployee(String file) {
//your exact same implementation
}
public static ArrayList<Employee> setEmployeeBaseSalary(String file, List<Employee> list) {
ArrayList<Employee> Emp = new ArrayList<>();
try (FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr)) {
Employee emp;
String line = br.readLine();
while (line != null) {
String[] data = line.split(",");
//Looking for an employee by the id read
emp = list.stream().filter(employee -> employee.getId().equals(data[0])).findFirst().orElse(null);
//If an employee with that id has been found then it's base salary is set
if (emp != null) {
emp.setBaseSalary(Double.parseDouble(data[1]));
}
line = br.readLine();
}
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
return Emp;
}
Test main
public static void main(String[] args) {
//Reading the list of employees
ArrayList<Employee> listEmployee = loadEmployee("a.txt");
//Setting the base salary for each employee
setEmployeeBaseSalary("b.txt", listEmployee);
//Retrieving the top three salary employees
List<Employee> listTopThreeEmployee = listEmployee.stream()
.sorted(Comparator.comparingDouble(Employee::getSalary).reversed()) //sorting each employee by their salary in reversed order (from the highest to the lowest)
.limit(3) //Limiting the stream to the top three results
.collect(Collectors.toList()); //Collecting the top three employees in a new list
System.out.println(listTopThreeEmployee);
}
In addition, you should add within your Employee class setter and getter methods to set up and retrieve the Employee's fields.
class Employee {
private String id;
private String name;
private int month;
private double baseSalary;
public Employee(String id, String name, int month) {
this.id = id;
this.name = name;
this.month = month;
this.baseSalary = 0;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public double getBaseSalary() {
return baseSalary;
}
public void setBaseSalary(double baseSalary) {
this.baseSalary = baseSalary;
}
public double getSalary() {
return this.month * this.baseSalary;
}
public String toString() {
return "(" + this.id + "-" + this.name + "-" + this.month + "-" + baseSalary + "-" + getSalary() + ")";
}
}
On a side note: variables representing currency should be declared as BigDecimal rather than double, as it is important to have an exact representation of the value rather than an approximation. In fact, the double precision tries to represent the value as closely as possible, but it's not said that it corresponds to the actual value assigned.
I am designing a group generator that takes in preferences such as “mix gender”, “mix nationality”... I am putting a list of student names, followed by nationality and gene set, in an arraylist. What is the easiest way to generate groups, based on user input, that each group consists of people from different nationalities, or balanced gender.
public ArrayList<String> readEachWord(String className)
{
ArrayList<String> readword = new ArrayList<String>();
Scanner sc2 = null;
try {
sc2 = new Scanner(new File(className + ".txt"));
} catch (FileNotFoundException e) {
System.out.println("error, didnt find file");
e.printStackTrace();
}
while (sc2.hasNextLine()) {
Scanner s2 = new Scanner(sc2.nextLine());
while (s2.hasNext()) {
String s = s2.next();
readword.add(s);
}
}
return readword;
}
I am using this to read a text file, and on each line, I have each student's name nationality and gender. I put them into an ArrayList and am right now trying to figure out how to evenly distribute them based on the user-desired group numbers.
I am using a txt file to store all the information since this group generator is customized for my school.
You can use the groupinBy method
basic tutorial
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
class Scratch {
public static void main(String[] args) {
String student1 = "Macie American Female";
String student2 = "Yago Brazilian Male";
String student3 = "Tom American Male";
List<String> students = Arrays.asList(student1, student2, student3);
System.out.println(groupByGender(students));
System.out.println(groupByNationality(students));
}
private static Map<String, List<Student>> groupByNationality(List<String> students) {
return students.stream().map(s -> mapToStudent(s)).collect(Collectors.groupingBy(Student::getNationality));
}
private static Map<String, List<Student>> groupByGender(List<String> students) {
return students.stream().map(s -> mapToStudent(s)).collect(Collectors.groupingBy(Student::getGender));
}
private static Student mapToStudent(String s) {
String[] ss = s.split(" ");
Student student = new Student();
student.setName(ss[0]);
student.setNationality(ss[1]);
student.setGender(ss[2]);
return student;
}
private static class Student {
String name;
String nationality;
String gender;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNationality() {
return nationality;
}
public void setNationality(String nationality) {
this.nationality = nationality;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
#Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", nationality='" + nationality + '\'' +
", gender='" + gender + '\'' +
'}';
}
}
}
First of all, it would be better if you put your while loop inside the try block because you don't want to get there if the file hasn't been found.
Second, you don't need to create a new instance of Scanner just to read every line. You can simply read your file word by word:
while (sc2.hasNext())
readword.add(sc2.next());
To group the students according to their nationality, you can do something like that:
String nationality = [UserInput] ;
List<String> group = new ArrayList<>();
for (int i = 0; i < readword.size(); i++)
if (readword.get(i + 1).equals(nationality)
group.add(readword.get(i));
Ive been trying to use a for loop to add instances of a driver to a driver array. Each driver has 3 basic variables that are gathered through the for loop. When the loop runs though, the details of the last driver are stored in all of the indexes of the array! I want to get it so that i can add each individual driver to the array.
public static void addDriver(Driver[] d) { //method using for loop to add drivers
for(int i = 0; i < d.length; i++ ) {
String name, DOB, occupation;
System.out.println("Please Enter Driver Name");
name = kb.nextLine();
System.out.println("Please Select Driver Occupation");
System.out.println("1: Chauffeur" + "\n2: Accountant");
int choice = kb.nextInt();
kb.nextLine();
if (choice == 1) {
occupation = "Chauffeur";
} else {
occupation = "Accountant";
}
System.out.println("Please Enter Driver D.O.B");
DOB = kb.nextLine();
d[i] = new Driver(name, occupation, DOB);
}
}
any and all help greatly appreciated!
edit...
here is the code from the main method, i get the size of the array from a separate method called driverNum.
public static void main(String[] args) {
int drivers = driverNum(); //Setting size of the array
Driver[] d = new Driver[drivers]; //creating new array using number of drivers to be insured
addDriver(d); //calling method to add drivers to array
for(int x = 0; x < d.length; x++)
{
System.out.println(d[x].toString());
}
}
here is the Driver class that i have been using...
public class Driver {
static String name, occupation, DOB;
public Driver()
{
name = "";
occupation = "";
DOB = "";
}
public Driver(String name, String occupation, String DOB)
{
this.name = name;
this.occupation = occupation;
this.DOB = DOB;
}
public void setName(String name)
{
this.name = name;
}
public String getName(Driver d)
{
return name;
}
public void setOccupation(String occupation)
{
this.occupation = occupation;
}
public String getOccupation()
{
return occupation;
}
public void setDOB(String DOB)
{
this.DOB = DOB;
}
public String getDOB()
{
return DOB;
}
public String toString()
{
String s;
s = "Name: " + name;
s = s + "\nOccupation: " + occupation;
s = s + "\nDOB: " + DOB;
return s;
}
}
Ive been scratching my head over this for a while now, because i thought it was correct. Thanks for the help so far!
In your Driver class, you defined your three global variables, name, occupation, and D.O.B as static. This means that whenever you change the value of that variable, it will change everywhere in the program, even if you create multiple instances of that class. Just take out the static declaration and that should solve your problem.
I made some projects with ArrayList. They have same problem with adding new object. My goal is to add new Object at specific location. For instance, each index hold four strings.
index 0: New York Times, 1234, New York, NY
index 1: NBCPhiladelphia, X123, Philadelphia, PA
index 2: FOX News, 0987, Los Angeles, LA
Suppose I want to add new one: CNN, 1230, Atlanta, GA. The location will be at index 1. Then other object will move in other index and so on... like this one:
index 0: New York Times, 1234, New York, NY
index 1: CNN, 1230, Atlanta, GA
index 2: NBCPhiladelphia, X123, Philadelphia, PA
index 3: FOX News, 0987, Los Angeles, LA
So far, my code seems not work to insert new one. I don't know how to find a way to fix this error.
public static void main(String[] args) {
ArrayList<NewsTV> newsTVList = new ArrayList<NewsTV>();
String nameToAdd = "CNN";
String idToAdd = "1234-123X";
String cityToAdd = "Atlanta";
String stateToAdd = "GA";
int indexToAdd = 6;
...... //This part, I add objects so don't worry about them.
newsTVList.add(indexToAdd, null);
insertObject(newsTVList, indexToAdd, nameToAdd, idToAdd, cityToAdd, stateToAdd);
public static void insertObject(ArrayList<NewsTV> np, int index, String n, String id,
String c, String s) {
for(NewsTV news: np) {
if(np.indexOf(index)) {
news.setName(n);
news.setISSN(id);
news.setCity(c);
news.setState(s);
}
}
}
First create POJO Class, here is Company
package com.appkart.array;
public class Company {
private String name;
private String id;
private String city;
private String state;
public Company(String name, String id, String city, String state) {
this.name = name;
this.id = id;
this.city = city;
this.state = state;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
#Override
public String toString() {
return name + ", " + id + ", " + city + ", " + state;
}
}
Then now add company into Arraylist as
package com.appkart.array;
import java.util.ArrayList;
public class TestCompany {
ArrayList<Company> companies = new ArrayList<Company>();
public void addCompany() {
Company newYorkTimes = new Company("New York Times", "1234",
"New York", "NY");
Company nbc = new Company("NBCPhiladelphia", "X123", "Philadelphia",
"PA");
Company fox = new Company("FOX News", "0987", "Los Angeles", "LA");
companies.add(newYorkTimes);
companies.add(nbc);
companies.add(fox);
printCompanyInfo();
}
public void addCompanyAtIndex(int index, Company company) {
companies.add(index, company);
printCompanyInfo();
}
public void printCompanyInfo() {
for (Company company : companies) {
System.out.println(company.toString());
}
}
public static void main(String[] args) {
TestCompany testCompany = new TestCompany();
testCompany.addCompany();
Company company = new Company("CNN", "1230", "Atlanta", "GA");
testCompany.addCompanyAtIndex(1, company);
}
}
When you use newsTVList.add(indexToAdd, null); you are adding a null item to your arraylist and when you use for(NewsTV news: np) {if(np.indexOf(index)) one of the np will be null and the program will throw a null pointer exception.
Create a new NewsTV object and initialize it with its values
String nameToAdd = "CNN";
String idToAdd = "1234-123X";
String cityToAdd = "Atlanta";
String stateToAdd = "GA";
Then call newsTVList.add(indexToAdd, <Your new NewsTV object> );
If you need the detail of the ArrayList.add(int index, E element) method look at the docs for the JSE 7
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
This is not supposed to be a client class. I'm just making a class for others to use. I'm using this for a Highschool. For example i have classes for the address, teacher, students, principal, roomnumber, etc..But its not compiling for some odd reason. I believe its because I'm not declaring a field but not sure.
import java.io.*;
public class HighSchool {
// Constructors
public HighSchool() { }
public HighSchool(String title, String teacher, int roomNumber, String period, String[] students, String address, String subjects ) {
this.title = title;
this.teacher = teacher;
this.roomNumber = roomNumber;
this.period = period;
this.String[] students = students;
this.String address =a ddress;
this.String subjects = subjects;
}
public class Classcourse (String title, String teacher, int roomNumber, String period, String[] students, String address, String subjects
private String period;) {
public String gettitle() {
return title;
}
public void settitle(String title) {
this.title = title;
}
public String getteacher() {
return teacher;
}
public void setteacher(String teacher) {
this.teacher = teacher;
}
public int getroomNumber() {
return roomNumber;
}
public void setroomNumber (int roomNumber) {
this.roomNumber = roomNumber;
}
public String getperiod() {
return getperiod();
}
public void setperiod (String period) {
this.period = period;
}
public String[] getstudents () {
return students[];
}
public void setstudents[] (String[] students
private String address;) {
this.students = students;
}
public String getaddress() {
return address;
}
public void setaddress (String address) {
this.address = address;
}
public String getsubjects() {
return subjects;
}
public void setsubjects (String subjects) {
this.subjects = subjects;
}
}
// modifier method
public void addstudents(String students) {
String[] newstudents = new String[students.length + 1];
for (int i = 0; i < students.length; i++) {
newstudents[i] = students[i];
}
newstudents[students.length] = student;
students = newstudents;
}
public boolean isInClass(String students) {
for (int i = 0; i < students.length; i++) {
if (students[i].equals(students)) {
return true;
}
}
return false;
}
// static creator method
public static HighSchool readFromInput() throws IOException {
BufferedReader kb = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a HighSchool title: ");
HighSchool newHighSchool = new HighSchool(kb.readLine());
String students = null;
do {
System.out.print("Enter a student, or press Enter to finish: ");
students = kb.readLine();
if (students != null){
newHighSchool.addstudents(students);
}
} while (students != null);
return newHighSchool;
}
// Variables (Fields)
private String title;
private String[] students;
}
In addition, you wrote something that doesn't make sense from the point of view of Java Compiler:
private String period;) {
- probably remove ")".
The second thing:
Take a look on the declaration of class Classcourse.
It rather sounds wrong, although it can be an issue of this site's editor or something...
An "overall" hint - java has a very "intelligent" compiler in the most of the cases it can say what's wrong exactly with your code, so, assuming you're a newbie in Java, try to understand what compiler says to you.
Good luck!
Some things I noticed about the code:
public String getperiod() {
return getperiod();
}
This code will cause a endless loop when you call this function.
private String address;) {
this.students = students;
}
The compiler will give an error about the ";)". Change it to "()" to fix this.
Furthermore, you should really tell us more about the errors it's giving you. We can't help you if you don't give us the compiler errors.