My program works if I initialize my Enum Cities as null but I want it to be Optional. I can make it Optional but then the class Address which is supposed to take Cities as one of it's parameters won't do so because Cities is not defined as Optional in the class Address but I can't change it so that the Optional is the parameter of this class and that it works
This is my enum class
public enum Cities {
NEWYORK("New York",10000),
LOSANGELES("Los Angeles",90000),
CHICAGO("Chicago",60000),
NEWORELANS("NEW Orlans",70000),
DALLAS("Dallas",75000);
private final String name;
private final Integer postalCode;
Cities(String name, Integer postalCode) {
this.name=name;
this.postalCode=postalCode;
}
It works like this
private static Address addressInput (Scanner scanner) {
ArrayList<Cities> cityList = new ArrayList<>();
Cities city = null;
do {
for (Cities cities : Cities.values()) {
System.out.println(cities);
cityList.add(cities);
}
String cityInput = dataInput(scanner, "Type in the name of one of the cities: ");
for (int j = 0; j < cityList.size(); j++) {
if (cityInput.equalsIgnoreCase(cityList.get(j).getName())) {
city = cityList.get(j);
}
}
if (city == null) {
System.out.println("Please select one of the cities on the list.");
}
} while (city == null);
String street = dataInput(scanner, "Name of the street: ");
String houseNumber = dataInput(scanner, "House number: ");
return new Address.Builder(city)
.atStreet(street)
.atHouseNumber(houseNumber)
.build();
}
But Adress constructor now won't accept city if it's Optional because it is defined differently in Adress class
private static Address addressInput (Scanner scanner) {
ArrayList<Cities> cityList = new ArrayList<>();
Optional<Cities> city = Optional.empty();
do {
for (Cities cities : Cities.values()) {
System.out.println(cities);
cityList.add(cities);
}
String cityInput = dataInput(scanner, "Unesite naziv jednog od ponuđenih gradova: ");
for (int j = 0; j < cityList.size(); j++) {
if (cityInput.equalsIgnoreCase(cityList.get(j).getName())) {
city = Optional.ofNullable(cityList.get(j));
}
}
if (city.isEmpty()) {
System.out.println("Molimo odabrati jedan od ponuđenih gradova.");
}
} while (city.isEmpty());
public class Address {
private String street;
private String houseNumber;
private Cities city;
public Address(Cities city,String street, String houseNumber) {
this.street = street;
this.houseNumber = houseNumber;
this.city=city;
}
public static class Builder {
Cities city;
String street;
String houseNumber;
public Builder (Cities city){
this.city=city;
}
public Builder atStreet (String street){
this.street=street;
return this;
}
public Builder atHouseNumber (String houseNumber){
this.houseNumber=houseNumber;
return this;
}
public Address build (){
Address address = new Address();
address.city=city;
address.houseNumber=houseNumber;
address.street=street;
return address;
}
}
How to edit class to accept Optional?
Using Optional here is probably not the best idea as other have mentioned in the comments above, but if you really wish as it's for learning purposes you can do something like this:
ArrayList<Cities> cityList = new ArrayList<>();
Optional<Cities> city = Optional.empty();
do {
for (Cities cities : Cities.values()) {
System.out.println(cities);
cityList.add(cities);
}
String cityInput = dataInput(scanner, "Type in the name of one of the cities: ");
for (int j = 0; j < cityList.size(); j++) {
if (cityInput.equalsIgnoreCase(cityList.get(j).getName())) {
city = Optional.ofNullable(cityList.get(j));
}
}
if (!city.isPresent()) {
System.out.println("Please select one of the cities on the list.");
}
} while (!city.isPresent());
String street = dataInput(scanner, "Name of the street: ");
String houseNumber = dataInput(scanner, "House number: ");
return new Address.Builder(city.get())
.atStreet(street)
.atHouseNumber(houseNumber)
.build();
By using optionals get() method you'll get it's value immediately but note that it will throw NoSuchElementException if no value is present. Usually it's not recommended to use get() to get Optional's value, but in this case it can be used as you're sure that Optional will be present because of the while condition.
Anyway, when you are not sure if optional is present then it's best to use alternative Optional methods to get it's value:
orElse() - Return the value if present, otherwise return other.
orElseGet(Supplier<? extends T> other) - Return the value if present, otherwise invoke other and return the result of that invocation.
orElseThrow(Supplier<? extends X> exceptionSupplier) - Return the contained value, if present, otherwise throw an exception to be created by the provided supplier.
Related
Getting stuck with my Travail System Project, Confusing a little bit about understanding that if there Classes called Bookable, Hotel and BookingSystem.
Hotel class is implements Bookable. Furthermore, BookingSystem Class is composition from Bookable, So, I need to create method at BookingSystem class which called addHotel.
what I must do about it to make a relationship between Hotel Class and BookingSystem Class.
Thanks In Advance.
Israa
Hotal Class:
public class Hotel implements Bookable {
private String name, location;
private int noOfRooms;
private double roomPrice;
private Date bookingDate;
private ArrayList<Integer> bookedRooms = new ArrayList<Integer>();
private ArrayList<Integer> numberOfrooms = new ArrayList<Integer>();
public Hotel() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public int getNoOfRooms() {
return noOfRooms;
}
public void setNoOfRooms(int noOfRooms) {
this.noOfRooms = noOfRooms;
}
public double getRoomPrice() {
return roomPrice;
}
public void setRoomPrice(double roomPrice) {
this.roomPrice = roomPrice;
}
public Date getBookingDate() {
return bookingDate;
}
public void setBookingDate(Date bookingDate) {
this.bookingDate = bookingDate;
}
public ArrayList<Integer> getBookedRooms() {
return bookedRooms;
}
public void setBookedRooms(ArrayList<Integer> bookedRooms) {
this.bookedRooms = bookedRooms;
}
public String Book() {
if ( numberOfrooms.size() != (bookedRooms.size())) {
for (int i = 0; i < bookedRooms.size(); i++) {
int oldVal = bookedRooms.get(i);
int newVal = oldVal + 1;
bookedRooms.add(bookedRooms.set(i, newVal));
}
}
return null;
}
}
Bookable class:
public interface Bookable {
public String Book();
}
BookingSytsem Class:
public class BookingSystem {
private ArrayList<Customer> customer = new ArrayList<Customer>();
private ArrayList<Bookable> bookable = new ArrayList<Bookable>();
private ArrayList<Operation> operation = new ArrayList<Operation>();
public BookingSystem() {
}
// **
public void addCustomer(String name, int id) {
Customer customers = new Customer(id, name);
customer.add(customers);
System.out.println("new customer " + customers.getName() + " added");
}
// **
public void deleteCustomer(String name, int id) {
Customer customers = new Customer(id, name);
if (customer.contains(name)) {
customer.remove(name);
}
System.out.println("Customer " + customers.getName() + " deleted");
}
public Customer findCustomer(int id) {
for (Customer c : customer) {
if (c.getId() == id) {
return c;
}
}
return null;
}
public void addHotel() {
Hotel H1 = new Hotel();
Scanner name = new Scanner(System.in);
System.out.println("Please Enter the name of Hotel: ");
String n1 = name.nextLine();
bookable.add(H1);
System.out.println("The Hotel " + name + "added");
}
public void makeABooking(Customer c, Bookable b) {
Scanner input =new Scanner(System.in);
System.out.println("Please Enter your name: ");
String name = input.nextLine();
System.out.println("Please Enter your ID: ");
int ID = input.nextInt();
while(true) {
if(ID == -1 && ID == 0) {
System.out.println("Invalid ID. Enter again: ");
name = input.nextLine();
System.out.println("Please Enter your ID: ");
ID = input.nextInt();
}
}
}
}
(Your question is more suitable to https://softwareengineering.stackexchange.com/ - recommend asking it there...)
General speaking it wouldn't make sense to have a Hotel without a name, location or number of rooms so I'd recommend adding a constructor with minimal required information:
public Hotel (String name, String location, int rooms) {
this.name = name;
this.location = location;
this.noOfRooms = rooms;
}
bookingDate makes no sense as a single property of a hotel but rather a property of each booked room so you have a design issue - this is not addressed here.
Again, roomPrice usually varies by room so in a robust solution this would be a property of a room not a hotel - not addressed here.
Why is there a noOfRooms and a numberOfRooms list. In fact, the numberOfRooms list doesn't make sense as a list. I'd just keep the noOfRooms and get rid of numberOfRooms.
An implied property, nbrOfAvailableRooms can be derived from noOfRooms - bookedRooms.size();
I would assume your bookedRooms is a list of room numbers which are booked but that's not possible to tell from your implementation. You should focus on what you want Book to do.
The Book interface method is not documented but it looks like it should simply take an available asset (room) and consider it booked. It should return a boolean success not a String - especially not null.
I recommend writing (in pseudo code) what you want a Book implementation to do - include that in question. That is the core issue you are having.
I'm trying to remove the object from an ArrayList of
type Contact class. I am trying to take input from users and want to
delete that object from ArrayList
public class Contacts {
private String name, phoneNumber;
public Contacts(){
}
public Contacts(String name, String phoneNumber) {
this.name = name;
this.phoneNumber = phoneNumber;
}
public String getName() {
return name;
}
public String getPhoneNumber() {
return phoneNumber;
}
#Override
public String toString() {
return "Contacts{" +
"name='" + name + '\'' +
", phoneNumber='" + phoneNumber + '\'' +
'}';
}
public static Contacts createContact(String name, String phoneNumber) {
return new Contacts(name, phoneNumber);
}
}
Here I tried to add objects with names and numbers and then print them and I want to delete a particular object.
public class Mobile {
ArrayList<Contacts> mycontacts;
public Mobile() {
this.mycontacts = new ArrayList<Contacts>();
}
public void addContacts() {
System.out.println("enter contact name");
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
System.out.println("enter contact number");
String number = sc.nextLine();
Contacts contacts = new Contacts(name, number);
mycontacts.add(contacts);
}
public void print() {
for (Contacts contacts : mycontacts) {
System.out.println(contacts.getName() + "->" + contacts.getPhoneNumber());
}
}
public String findcontact() {
Scanner scanner = new Scanner(System.in);
System.out.println("enter contact name");
String name = scanner.nextLine();
System.out.println("enter phone number");
String number = scanner.nextLine();
Contacts contacts = new Contacts(name, number);
int x = mycontacts.indexOf(contacts);
return mycontacts.get(x).getName();
}
public void remove() {
Scanner scanner = new Scanner(System.in);
System.out.println("enter contact name");
String name = scanner.nextLine();
System.out.println("enter contact number");
String number = scanner.nextLine();
Contacts contacts = new Contacts(name, number);
Iterator<Contacts> itr = mycontacts.iterator();
while (itr.hasNext()){
Contacts contacts1 = itr.next();
System.out.println(contacts1);
if (contacts1==contacts){
itr.remove();
}
}
}
}
You need to implement the equals method on your Contacts class, something like this
public boolean equals(Object other){
if(other instanceof Contract){
Contract otherC = (Contract)other;
return this.name.equals(otherC.name) && this.phoneNumber.equals(otherC.phoneNumber);
}
return false;
}
Java isn't my strong suit, but I think you can fix it like this:
Iterator<Contacts> itr = mycontacts.iterator();
while (itr.hasNext()){
Contacts contacts1 = itr.next();
System.out.println(contacts1);
if (contacts1.getName()==contacts.getName() && contacts1.getPhoneNumber() == contacts.getPhoneNumber()){
itr.remove();
}
}
Or simplified:
mycontacts.removeIf(i -> i.getName()==contacts.getName() && i.getPhoneNumber()==contacts.getPhoneNumber());
I think what is happening is that in this comparison: if (contacts1==contacts)
These will never be equal, as they are different objects, but they have the same values for their class variables.
https://www.baeldung.com/java-comparing-objects
the value of those objects is not 1. Rather it is their memory addresses in the stack that are different since both objects were created using the new operator.
edit: actually, another answer showed up while I was answering, which is better. I'll leave mine up since I think I gave more explanation.
There are two ways to remove an element from an ArrayList:
remove(Object object)
remove(int index)
So if you're using the name as the key, it could look something like:
public void removeContact(String name) {
for(contact : mycontacts) {
if(contact.name == name) {
mycontacts.remove(contact)
}
}
}
I tried using the following code, it worked. Thank you all who helped me. :)
for (Contacts mycontact : mycontacts) {
if (mycontact.getName().equals(name)) {
System.out.println("removed contact"+mycontact.getName()+"->"+mycontact.getPhoneNumber());
mycontacts.remove(mycontact);
}
else{
System.out.println("error deleting contact");
}
}
import java.util.Arrays;
import java.util.Scanner;
public class employee{
public String name;
public class employee_address{
String street_name;
String city;
String zipcode;
String state;
String country;
}
public static void main(String []args){
Scanner user_input = new Scanner(System.in);
int no_of_employees = user_input.nextInt();
employee[] employees_list = new employee[no_of_employees];
for(int i = 0;i < no_of_employees;i++){
employees_list[i].name = user_input.nextLine();
employees_list[I].employee_address = // this is it ?
}
}
}
In the code above I do understand that the employee_address is a class and can't be accessed
directly without an instance being created like in the code, that makes no sense. but how can I create an instance of the employee_address class that is associate with each employee.
like in the code above 'employee_address' is associated with every employee but how can the class 'employee_address' be initialised and how can I set the street_name, city and the rest of the members in the address class. any ideas would be appreciated.
You can't directly create an instance of inner class, the reason because since it is the property of another instance we always need to use it though the instance of parent variable.
Let's say you have a class, which have two propeties:
public class Employee {
public String name;
public EmployeeAddress emAddress;
}
to access emAddress you need to use through the instance of Employee class, for example -
Employee object = new Employee();
EmployeeAddress empAdd = object.new EmployeeAddress();
Full code:
public class Employee {
public String name;
public EmployeeAddress emAddress;
public class EmployeeAddress {
String street_name;
String city;
String zipcode;
String state;
String country;
public String getStreet_name() {
return street_name;
}
public void setStreet_name(String street_name) {
this.street_name = street_name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getZipcode() {
return zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
#Override
public String toString() {
return "EmployeeAddress [street_name=" + street_name + ", city=" + city + ", zipcode=" + zipcode
+ ", state=" + state + ", country=" + country + "]";
}
}
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int no_of_employees = user_input.nextInt(); // let's say no_of_employees = 1
Employee[] employees = new Employee[no_of_employees];
for (int i = 0; i < no_of_employees; i++) {
Employee object = new Employee();
object.setName("Virat Kohli");
EmployeeAddress empAdd = object.new EmployeeAddress();
empAdd.setCity("New Delhi");
empAdd.setCountry("India");
empAdd.setState("Delhi");
empAdd.setStreet_name("Chandni Chalk");
empAdd.setZipcode("741124");
object.setEmAddress(emAddress);
employees[i] = object;
}
System.out.println(employees[0]);
user_input.close();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public EmployeeAddress getEmAddress() {
return emAddress;
}
#Override
public String toString() {
return "Employee [name=" + name + ", emAddress=" + emAddress + "]";
}
public void setEmAddress(EmployeeAddress emAddress) {
this.emAddress = emAddress;
}
}
I have modified your code to sonar standard.
Below code uses Java naming conventions (which your code does not).
Notes after the code.
import java.util.Scanner;
public class Employee {
private String name;
private EmployeeAddress address;
public class EmployeeAddress {
String streetName;
String city;
String zipcode;
String state;
String country;
}
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
int noOfEmployees = userInput.nextInt();
Employee[] employeesList = new Employee[noOfEmployees];
for (int i = 0; i < noOfEmployees; i++) {
employeesList[i] = new Employee();
employeesList[i].name = userInput.nextLine();
EmployeeAddress employeeAddress = employeesList[i].new EmployeeAddress();
employeesList[i].address = employeeAddress;
employeesList[i].address.streetName = userInput.nextLine();
}
}
}
An inner class is a normal class. It is not a member of its enclosing class. If you want class Employee to have an [employee] address, as well as a [employee] name, you need to add another member variable to class Employee whose type is EmployeeAdress.
Employee[] employeesList = new Employee[noOfEmployees];
The above line creates an array but every element in the array is null. Hence you need to first create a Employee object and assign it to an element of the array. Hence the following line in my code, above:
employeesList[i] = new Employee();
Since EmployeeAddress is not a static class, in order to create a new instance, you first need an instance of the enclosing class, i.e. Employee. Hence the following line in the above code.
EmployeeAddress employeeAddress = employeesList[i].new EmployeeAddress();
Since all your code is in class Employee, in method main you can directly access the members of both class Employee and EmployeeAddress. Nonetheless you need to be aware of the different access modifiers in java.
A few hints:
stick to naming conventions: class names in Java start with capital letters
use (class) definitions before using them (collect them at the top if not inconventient)
if you are sure you want to use inner classes, set them static, unless you want them to be entangled in generics.
Usually normal classes in each their own file are a lot more flexible and far easier to use
if you use objects that only carry public data, try to use final keyword and initialize them ASAP
use proper objects first, and after finishing them assign them to arrays. avan better would be the use of ArrayList and the like
if Employee contains EmployeeAddress, it should initialize it if conventient. so an object is always responsible for its own stuff
Use try/resrouce/catch
scanner.nextInt() can be problematic with newline/line breaks. For user input better readLine() and parse input
Code:
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Scanner;
public class Employee {
static public class EmployeeAddress {
public final String street_name;
public final String city;
public final String zipcode;
public final String state;
public final String country;
public EmployeeAddress(final Scanner pScanner, final PrintStream pOutPS) {
street_name = readLine(pScanner, pOutPS, "Please enter Street Name:");
city = readLine(pScanner, pOutPS, "Please enter City Name:");
zipcode = readLine(pScanner, pOutPS, "Please enter Zip Code:");
state = readLine(pScanner, pOutPS, "Please enter State:");
country = readLine(pScanner, pOutPS, "Please enter Country:");
}
}
static public String readLine(final Scanner pScanner, final PrintStream pOutPS, final String pPrompt) {
pOutPS.print(pPrompt);
final String value = pScanner.nextLine();
pOutPS.println();
return value;
}
static public int readInt(final Scanner pScanner, final PrintStream pOutPS, final String pPrompt) {
return Integer.parseInt(readLine(pScanner, pOutPS, pPrompt));
}
public final String name;
public final EmployeeAddress address;
public Employee(final Scanner pScanner, final PrintStream pOutPS) {
name = readLine(pScanner, pOutPS, "Please enter Employee Name: ");
System.out.println("Name: " + name);
address = new EmployeeAddress(pScanner, pOutPS);
}
public static void main(final String[] args) {
try (final Scanner user_input = new Scanner(System.in);
final PrintStream output = System.out;) {
final int no_of_employees = readInt(user_input, output, "Please enter number of users: ");
final Employee[] employees_list = new Employee[no_of_employees]; // either this line
final ArrayList<Employee> employees = new ArrayList<>(); // or this line
for (int i = 0; i < no_of_employees; i++) {
output.println("Creating user #" + (i + 1) + "...");
final Employee newEmployeeWithAddress = new Employee(user_input, output);
employees_list[i] = newEmployeeWithAddress; // either this line
employees.add(newEmployeeWithAddress); // or this line
}
}
}
}
The exercise is to have a class named Tenant that will be used to store values of tenants for an apartment. In the main class Prog2 I am trying to create an ArrayList that can hold 4 different values, all regarding the tenant class, which are - the tenant's name, apartment number, initial first payment, and monthly payment. I want to be able to print these values out in separate lines that will provide all 4 pieces of information per tenant - followed by a blank line, and then the same 4 pieces of information for another tenant if there is another one. I can get the program to prompt the questions correctly, but then all I get are nulls and 0's printed out (see below at comment). I appreciate all the help - I'm not the best at this.
// this class is the tenant class that passes all the tenant's
information
public class Tenant {
private String firstName;
private String lastName;
private String aptNumber;
private double yearlyRent;
private String fullName;
private double firstPayment;
private double monthlyPayment;
public Tenant(String name, String aptNum, double fPayment, double
mPayment){
name = fullName;
aptNum = aptNumber;
fPayment = firstPayment;
mPayment= monthlyPayment;
}
public Tenant() {
}
public void setFirstName(String name) {
firstName = name;
}
public void setLastName(String lName) {
lastName= lName;
}
public void setAptNumber(String apt) {
aptNumber = apt;
}
public void setRent(double rent) {
yearlyRent = rent;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getAptNumber() {
return aptNumber;
}
public double getRent() {
return yearlyRent;
}
public double getFirstPayment() {
double monthlyRent = yearlyRent/12;
firstPayment = monthlyRent * 3;
return firstPayment;
}
public double getmonthlyPayment() {
double firstAndLast = yearlyRent/12;
monthlyPayment = (yearlyRent - firstAndLast)/11;
return monthlyPayment;
}
public String getFullName(){
fullName = firstName + " " + lastName;
return fullName;
}
}
// The below class contains the main method
public class Prog2 {
public static double getDouble(Scanner scan) {
System.out.println("Enter yearly rent:");
while (!scan.hasNextDouble()) {
scan.next();
System.out.println("Error: please enter a numeric
value");
}
return scan.nextDouble();
}
public static void main(String[] args) {
Tenant tnt = new Tenant();
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of tenenats:");
int numTenants = scan.nextInt();
ArrayList<Tenant> list = new ArrayList<Tenant>();
for (int i = 0; i<numTenants; i++) {
System.out.println("Enter first name:");
tnt.setFirstName(scan.next());
System.out.println("Enter last name:");
tnt.setLastName(scan.next());
System.out.println("Enter apt number:");
tnt.setAptNumber(scan.next());
tnt.setRent(getDouble(scan));
list.add(new Tenant(tnt.getFullName(), tnt.getAptNumber(),
tnt.getFirstPayment(), tnt.getmonthlyPayment()));
}
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).getFullName());
System.out.println(list.get(i).getAptNumber());
System.out.println(list.get(i).getFirstPayment());
System.out.println(list.get(i).getmonthlyPayment());
System.out.println();
}
}
}
// this prints out:
null null
null
0.0
0.0
null null
null
0.0
0.0
The issue is with the first constructor in the Tenant class. Remember that the = operator assigns the value of the right operand to the variable in the left operand. In your case the code should look like this:
public Tenant(
String name,
String aptNum,
double fPayment,
double mPayment)
{
fullName = name;
aptNumber = aptNum;
firstPayment = fPayment;
monthlyPayment = mPayment;
}
What I typically do with constructors is name the parameters after the field, then on the left side of the field assignments use this to refer to the field as opposed to the parameter. This ends up looking much clearer:
public Tenant(
String fullName,
String aptNumber,
double firstPayment,
double monthlyPayment)
{
this.fullName = fullname;
this.aptNumber = aptNumber;
this.firstPayment = firstPayment;
this.monthlyPayment = monthlyPayment;
}
this can be tricky to use but this is an example where it can clear things up.
Many things are wrong with your code .
Constructor of
public Tenant(String name, String aptNum, double fPayment, double
mPayment){
name = fullName;
aptNum = aptNumber;
fPayment = firstPayment;
mPayment= monthlyPayment;
}
here your not just assigning null values to your function parameeters, instead of assigning values to your class fields from function parameters.
Also, when you are calling function getFullName() , it will return null as firstName and lastName fields are not initialized.
So, you need to modify your constructor to -
public Tenant(String firstNamename, String lastName, String aptNum, double fPayment, double
mPayment){
this.firstName = firstNamename;
this.lastName = lastName;
this.aptNumber = aptNum;
this.firstPayment = fPayment;
this.monthlyPayment = mPayment;
this.fullName = getFullName();
}
also in for loop , you need to change
list.add(new Tenant(tnt.getFullName(), tnt.getAptNumber(),
tnt.getFirstPayment(), tnt.getmonthlyPayment()));
to -
list.add(new Tenant(tnt.getFirstName(),tnt.getLastName(), tnt.getAptNumber(),
tnt.getFirstPayment(), tnt.getmonthlyPayment()));
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.