Particular Format Table in Java - java

Table Format
I have to create a program that sorts all employees by last name and prints them to the screen in a tabular format.
I am having an issue creating a table in the format attached above. Please see what I have and can help out, at this point I don't know how to set it up so the final output looks like the table attached. Thank you.
public static void main(String[] args)
{
Employee[] employees = {
new Employee("John","Johnson","Manager",20161231),
new Employee("Tou","Xiong","Software Engineer",20161005),
new Employee("Michaela", "Michaelson", "District Manager", 20151219),
new Employee("Jake","Jacobson","Programmer",00000000),
new Employee("Jackquelyn", "Jackson", "DBA",00000000),
new Employee("Sally","Webber","Web Developer",20151218)
};
// get List view of the Employees
List<Employee> list = Arrays.asList(employees);
// display all Employees
System.out.println("Complete Employee list:");
list.stream().forEach(System.out::println);
// Functions for getting first and last names from an Employee
Function<Employee, String> byFirstName = Employee::getFirstName;
Function<Employee, String> byLastName = Employee::getLastName;
// Comparator for comparing Employees by first name then last name
Comparator<Employee> lastThenFirst =
Comparator.comparing(byLastName).thenComparing(byFirstName);
// sort employees by last name, then first name
System.out.printf(
"%nEmployees in ascending order by last name then first:%n");
list.stream()
.sorted(lastThenFirst)
.forEach(System.out::println);
}
}
class Employee
{
private String firstName;
private String lastName;
private String department;
private double separationDate;
// constructor
public Employee(String firstName, String lastName,
String department,double separationDate)
{
this.firstName = firstName;
this.lastName = lastName;
this.department = department;
this.separationDate=separationDate;
}
// set firstName
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
// get firstName
public String getFirstName()
{
return firstName;
}
// set lastName
public void setLastName(String lastName)
{
this.lastName = lastName;
}
// get lastName
public String getLastName()
{
return lastName;
}
// set department
public void setDepartment(String department)
{
this.department = department;
}
// get department
public String getDepartment()
{
return department;
}
public void setseparationDate(double separationDate)
{
this.separationDate = separationDate;
}
// get salary
public double getseparationDate()
{
return separationDate;
}
// return Employee's first and last name combined
public String getName()
{
return String.format("%s %s", getFirstName(), getLastName());
}
// return a String containing the Employee's information
#Override
public String toString()
{
return String.format("%-8s %-8s %s %8.0f",
getFirstName(), getLastName(), getDepartment(),getseparationDate());
}
}```

You can accomplish this by using a combination of the String#format() method and the System.out.printf() method for formatting your particular Strings to the console window.
First it would be nice if you modify your Employee class so that the separationDate is of int type and not of double type. This would of course also include the Constructor as well as the Getter and Setter methods for this class instance variable. Adding a Getter method to your Employee class to convert this integer value to a string date format wouldn't be a bad idea either or just use a date string altogether instead of a numerical value for your separationDate instance variable. Never the less... your class could be modified to something like this where either or could be acquired:
public class Employee {
private String firstName;
private String lastName;
private String department;
private int separationDate;
// constructor
public Employee(String firstName, String lastName,
String department, int separationDate) {
this.firstName = firstName;
this.lastName = lastName;
this.department = department;
this.separationDate = separationDate;
}
// set firstName
public void setFirstName(String firstName) {
this.firstName = firstName;
}
// get firstName
public String getFirstName() {
return firstName;
}
// set lastName
public void setLastName(String lastName) {
this.lastName = lastName;
}
// Get Employee Full Name
public String getFullName() {
return this.firstName + " " + this.lastName;
}
// get lastName
public String getLastName() {
return lastName;
}
// set department
public void setDepartment(String department) {
this.department = department;
}
// get department
public String getDepartment() {
return department;
}
public void setseparationDate(int separationDate) {
this.separationDate = separationDate;
}
// Get Separation Date (As String)
public String getseparationDate() {
String dateString = "";
if (this.separationDate != 0) {
String date = String.valueOf(this.separationDate);
dateString = date.substring(0, 4) + "-" + date.substring(4, 6) + "-" + date.substring(6, 8);
}
return dateString;
}
public int getseparationDateAsInt() {
return this.separationDate;
}
// return Employee's first and last name combined
public String getName() {
return String.format("%s %s", getFirstName(), getLastName());
}
// return a String containing the Employee's information
#Override
public String toString() {
return new StringBuilder(firstName).append(", ").append(lastName).append(", ")
.append(department).append(", ").append(separationDate).toString();
}
/**
* Similar to the toString() method except it will return an object instance
* as string in a table style format.<br>
*
* #param options (Optional - Boolean - Two Options)<pre>
*
* addHeader - If true is supplied then the Object instance string
* id prefixed with an underlined Header String. If
* null or nothing is supplied then no header is
* provided.
*
* addFinalUnderline - If true is supplied then an underline is added to
* the Onject instance string. If null or nothing is
* supplied then no underline is provided under the
* table. If this optional parameter is supplied then
* a boolean value (or null) <u>must</u> be supplied to the
* 'addHeader' parameter.</pre>
*
* #return (String) An Object instance String. A toString in table style format.
*/
public String toTableString(Boolean... options) {
boolean addHeader = false;
boolean addFinalUnderline = false;
if (options.length > 0) {
if (options.length >= 1 && options[0] != null) {
addHeader = options[0];
}
if (options.length >= 2 && options[1] != null) {
addFinalUnderline = options[1];
}
}
String ls = System.lineSeparator();
StringBuilder sb = new StringBuilder("");
String header = String.format("%-25s| %-20s| %-15s", "Name", "Position", "Separation Date");
String underline = String.join("", java.util.Collections.nCopies(header.length(), "-"));
if (addHeader) {
sb.append(underline).append(ls);
sb.append(header).append(ls);
sb.append(underline).append(ls);
}
sb.append(String.format("%-25s| %-20s| %-15s", getName(),
getDepartment(), getseparationDate()));
if (addFinalUnderline) {
sb.append(ls).append(underline);
}
return sb.toString();
}
}
Your instances of Employee are held as elements within the Employee Array named employees and now you want to sort them. This can be done with the java.util.Arrays.sort() method, for example:
java.util.Arrays.sort(employees, new java.util.Comparator<Employee>() {
#Override
public int compare(Employee first, Employee second) {
return first.getName().compareTo(second.getName());
}
});
Since you have already created the getName() method (which is used to compare in the above code) within the Employee class the sort would take care of first and last name sorting should last names be the same.
You're already familiar with the String formatting methods so I'm not going to bore you with that anymore. To get the table you want ( or similar to it) then you can do it this way:
Employee[] employees = {
new Employee("John", "Johnson", "Manager", 20161231),
new Employee("Tou", "Xiong", "Software Engineer", 20161005),
new Employee("Michaela", "Michaelson", "District Manager", 20151219),
new Employee("Jake", "Jacobson", "Programmer", 00000000),
new Employee("John", "Jackson", "Coffee Mole", 20161012),
new Employee("Jackquelyn", "Jackson", "DBA", 00000000),
new Employee("Sally", "Webber", "Web Developer", 20151218)
};
// Sort the above Object Array (employees) by the employee's first name.
java.util.Arrays.sort(employees, new java.util.Comparator<Employee>() {
#Override
public int compare(Employee first, Employee second) {
return first.getName().compareTo(second.getName());
}
});
// Build the Header string
String header = String.format("%-25s| %-20s| %-15s", "Name", "Position", "Separation Date");
// Build the Header Underline string
String underline = String.join("", java.util.Collections.nCopies(header.length(), "-"));
System.out.println(underline);
System.out.println(header);
System.out.println(underline);
// Build the table data strings
for (Employee empl : employees) {
System.out.printf("%-25s| %-20s| %-15s%n", empl.getName(),
empl.getDepartment(), empl.getseparationDate());
}
System.out.println(underline); // Table underline to indicate End Of Table
The Console Window should display:
------------------------------------------------------------------
Name | Position | Separation Date
------------------------------------------------------------------
Jackquelyn Jackson | DBA |
Jake Jacobson | Programmer |
John Jackson | Coffee Mole | 2016-10-12
John Johnson | Manager | 2016-12-31
Michaela Michaelson | District Manager | 2015-12-19
Sally Webber | Web Developer | 2015-12-18
Tou Xiong | Software Engineer | 2016-10-05
------------------------------------------------------------------
In the above Employee class code, you may have noticed a method added named toTableString(). This method was added to the class to assist with displaying Employee object instances in a table format to the console Window (read the method's javadoc). It could be used something like this:
Employee[] employees = {
new Employee("John", "Johnson", "Manager", 20161231),
new Employee("Tou", "Xiong", "Software Engineer", 20161005),
new Employee("Michaela", "Michaelson", "District Manager", 20151219),
new Employee("Jake", "Jacobson", "Programmer", 00000000),
new Employee("John", "Jackson", "Coffee Mole", 20161012),
new Employee("Jackquelyn", "Jackson", "DBA", 00000000),
new Employee("Sally", "Webber", "Web Developer", 20151218)
};
// Sort the above Object Array (employees) by the employee's first name.
java.util.Arrays.sort(employees, new java.util.Comparator<Employee>() {
#Override
public int compare(Employee first, Employee second) {
return first.getName().compareTo(second.getName());
}
});
// Display the table in Console Window.
int cnt = 1;
for (Employee empl : employees) {
if (cnt == 1) {
System.out.println(empl.toTableString(true));
}
else {
if ((cnt) == employees.length) {
System.out.println(empl.toTableString(null, true));
}
else {
System.out.println(empl.toTableString());
}
}
cnt++;
}
The Console Window should display:
------------------------------------------------------------------
Name | Position | Separation Date
------------------------------------------------------------------
Jackquelyn Jackson | DBA |
Jake Jacobson | Programmer |
John Jackson | Coffee Mole | 2016-10-12
John Johnson | Manager | 2016-12-31
Michaela Michaelson | District Manager | 2015-12-19
Sally Webber | Web Developer | 2015-12-18
Tou Xiong | Software Engineer | 2016-10-05
------------------------------------------------------------------

Related

how do i update firstName in

i dont know how to add an update firstName function with my code. i am fairly new.
public class Contact {
private final String contactID;
private String firstName;
private String lastName;
private String Number;
private String Address;
private static AtomicLong idGenerator = new AtomicLong();
//CONSTRUCTOR
/*
* The constructor takes first name, last name, phone number, and address as parameters.
* The first thing it does is generates a new ID for the contactID field.
*
* First name and last name are checked for null condition or blank fields. If either of
* those conditions exist, fill in the field with the phrase "NULL" so that something exists
* to protect data integrity while making it clear it is a placeholder.
* In both cases, if the first or last name is greater than 10 characters, truncate it
* so that only the first 10 characters are used.
*
* For the number field, if the phone number is not exactly 10 characters then fill it with
* the placeholder '5555555555'.
*
* Address is like first and last names. If it is blank or null, set it to "NULL".
* If it is more than 30 characters, truncate to the first 30 characters.
*/
public Contact(String firstName, String lastName, String number, String address) {
//CONTACTID
//Contact ID is generated when the constructor is called. It is set as a final variable and has
//no other getter or setter so there should be no way to change it.
//The idGenerator is static to prevent duplicates across all contacts.
this.contactID = String.valueOf(idGenerator.getAndIncrement());
//FIRSTNAME
if (firstName == null || firstName.isBlank()) {
this.firstName = "NULL";
//If first name is longer than 10 characters, just grab the first 10 characters
} else if(firstName.length() > 10) {
this.firstName = firstName.substring(0, 10);
} else {
this.firstName = firstName;
}
//LASTNAME
if (lastName == null || lastName.isBlank()) {
this.lastName = "NULL";
} else if(lastName.length() > 10) {
this.lastName = lastName.substring(0,10);
} else {
this.lastName = lastName;
}
//NUMBER
if (number == null || number.isBlank() || number.length() != 10) {
this.Number = "5555555555";
} else {
this.Number = number;
}
//ADDRESS
if (address == null || address.isBlank()) {
this.Address = "NULL";
} else if(address.length() > 30) {
this.Address = address.substring(0,30);
} else {
this.Address = address;
}
}
//GETTERS
public String getContactID() {
return contactID;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getNumber() {
return Number;
}
public String getAddress() {
return Address;
}
}
package ContactService;
import java.util.ArrayList;
public class ContactService {
//Start with an ArrayList of contacts to hold the list of contacts
ArrayList<Contact> contactList = new ArrayList<Contact>();
//Display the full list of contacts to the console for error checking.
public void displayContactList() {
for(int counter = 0; counter < contactList.size(); counter++) {
System.out.println("\t Contact ID: " + contactList.get(counter).getContactID());
System.out.println("\t First Name: " + contactList.get(counter).getFirstName());
System.out.println("\t Last Name: " + contactList.get(counter).getLastName());
System.out.println("\t Phone Number: " + contactList.get(counter).getNumber());
System.out.println("\t Address: " + contactList.get(counter).getAddress() + "\n");
}
}
//Adds a new contact using the Contact constructor, then assign the new contact to the list.
public void addContact(String firstName, String lastName, String number, String address) {
// Create the new contact
Contact contact = new Contact(firstName, lastName, number, address);
contactList.add(contact);
}
public void removeContact (String firstName, String lastName, String number, String address) {
Contact contact = new Contact (firstName, lastName, number, address);
contactList.remove(contact);
}
public void updateFirstName {
}
}
how do i get the updateFirstName function to work. i need to be able to update the first name within a contact, but i dont know if i need to create a new contact like what was done in the add and remove contact functions. ive tried contact.setfirstname = new firstName but that did not work and i am at a loss on what to do.

Java - Enumeration as Optional

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.

how to add strings from different arrays into one array in java

Hello I'm a bit confused with some coding problem I am trying to solve.
I have a few string arrays:
String[] firstNames= {"Fred","John","Amir", "James","Bob","Jay","Amber"};
String[] lastNames = {"Bond","Kates","Memar", "White","Marley","Brown","Nogofski"};
String[] idNumbers = {"R111111","A222222","AB11111", "KR22121","V311133","L242434","P102432"};
String[] employeeNum = {"1111","2222","3333", "4444","5555","6666","7777"};
I have to create one array and somehow organize the corresponding pieces of information provided above in the method Employee[] list = new Employee[firstNames.length];
list = listOfEmployees(firstNames,lastNames,idNumbers); // create the list of employees in one array
I started writing out the method:
public static Employee[] listOfEmployees(String[] firstName, String[]
lastName, String[] idNumber){
}
but not sure how to approach this. also not sure if my parameters are correct.
the end result is supposed to look like this:
Employee #1
first name:Fred Last Name:Bond
Id number:R111111
.
.
.
Employee #2
first name:John Last Name:Kates
Id number:A222222
and so on..
thanks in advance.
EDIT:
Employee class:
public class Employee{
private String firstName;
private String lastName;
private String idNumber;
private String employeeNumber;
private int employeeCount;
/**
* Constructor
* #param firstName first name
* #param lastName last name
* #param idNumber id number
*/
public Employee(String firstName, String lastName, String idNumber){
this.firstName = firstName;
this.lastName = lastName;
this.idNumber = idNumber;
employeeCount = 0;
}
/**
* Accessors here
*/
public String getFirstName(){
return firstName;
}
public String getLastName(){
return lastName;
}
public String getIdNumber(){
return idNumber;
}
public String getEmployeeNumber(){
return employeeNumber;
}
// mutators here
/**
* #param firstName first name
*/
public void setFirstName(String firstName){
this.firstName = firstName;
}
/**
* #param lastName last name
*/
public void setLastName(String lastName){
this.lastName = lastName;
}
/**
* #param idNumber id number
*/
public void setIdNumber(String idNumber){
this.idNumber = idNumber;
}
/**
* #param employeeNumber employee number
*/
public void setEmployeeNumber(String employeeNumber){
this.employeeNumber = "";
}
#Override
public String toString(){
String result = "First name: " + getFirstName() + "\nLast name: " + getLastName()
+ "\nId number: " + getIdNumber() + "\nEmployee number: ";
if(getEmployeeNumber() == null){
return result + "No employee number has been assigned yet!";
}
return result + getEmployeeNumber();
}
}
Please try the following:
private static Employee[] listOfEmployees(String[] firstNames, String[] lastNames, String[] idNumbers){
Employee[] list = new Employee[firstNames.length];
for(int i=0; i<list.length; i++){
list[i]=new Employee(firstNames[i], lastNames[i], idNumbers[i]);
}
return list;
}
To print the array returned by the above function, you may use:
private static void printEmployees(Employee[] employees){
for (Employee employee : employees) {
System.out.println("ID: "+employee.getIdNumber());
System.out.println("Name : "+employee.getFirstName()+" "+employee.getLastName());
System.out.println("------------------------------------");
}
}
And call them by following statement:
printEmployees(listOfEmployees(firstNames,lastNames,idNumbers));
Do a for loop and use the Employee constructor to initialize the objects:
Employee[] list = new Employee[firstNames.length];
for (int i = 0; i < firstName.length; i++) {
list[i] = new Employee(firstName[i], lastName[i] ...
}
Try this
public class Test{
public static void main(String[] args){
String[] firstNames= {"Fred","John","Amir", "James","Bob","Jay","Amber"};
String[] lastNames = {"Bond","Kates","Memar", "White","Marley","Brown","Nogofski"};
String[] idNumbers = {"R111111","A222222","AB11111", "KR22121","V311133","L242434","P102432"};
String[] employeeNum = {"1111","2222","3333", "4444","5555","6666","7777"};
List<Employee> list = new ArrayList<>();
for(int i=0;i<firstName.length();i++){
list.add(new(Employee(firstName[i],lastName[i],idNumbers[i],employeeNumber[i]))}
}}

Adding and setting new object in ArrayList at specific index (JAVA)

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

Passing a comma delimited string into a class [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Here is what I have so far in my code
public class Person {
public Person()
{
String person = "";
int age = 0;
String city = "";
int sibCount = 0;
// make an instance field for name, city, age, and siblingCount
Person person = new Person();
Person age = new Person();
Person city = new Person();
Person sibCount = new Person();
}
// make a method called parseCommaDelim
public void parseCommaDelim(String[] args){
// return a Person instance UNSURE HERE
}
// make a toString method
public String toString()
{
String str = "person" + person + "age" + age + "city" + city;
return str;
}
}
}
I am trying return a person instance and I am not sure how to do it. I tried 'return Person;' and my code did not like it.
My toString method is not working either because it does not know what person, age, or city is, and I am not sure why.
What you want to achieve is probably something along the following lines:
public class Person {
// fields
private String person = "";
private int age = 0;
private String city = "";
private int sibCount = 0;
// constructor
public Person() {
}
// public access methods (getters)
public String getPerson() {
return this.person;
}
public int getAge() {
return this.age;
}
public String getCity() {
return this.city;
}
public int getSibCount() {
return this.sibCount;
}
// toString
public String toString() {
return "person: " + person + ", age: " + age + ", city: " + city;
// factory method
public static Person parseCommaDelim(String s) {
String[] tokens = s.split(",");
Person instance = new Person();
instance.person = tokens[0];
instance.age = Integer.parseInt(tokens[1];
instance.city = tokens[2];
// ...
return instance;
}
}
The field person should probably renamed to name. Depending wether you want to make your class immutable or not you may want to add either a constructor which takes all parameters as parameters:
public Person(String name, int age, String city, int sibCount) {
this.name = name;
this.age = age;
this.city = city;
this.sibCount = sibCount;
}
or add setters for the changable fields, for example:
public void setCity(String city) {
this.city = city;
}
btw. with above constructor you could modify the factory to the following slightly cleaner code:
public static Person parseCommaDelim(String s) {
String[] tokens = s.split(",");
String person = tokens[0];
int age = Integer.parseInt(tokens[1];
String city = tokens[2];
int sibCount = Integer.parseInt(tokens[3]);
return new Person(person, age, city, sibCount);
}
public class Person {
public String person;
public int age;
public String city;
public int sibCount;
public Person()
{
person = "";
age = 0;
city = "";
sibCount = 0;
}
// make a method called parseCommaDelim
public String parseCommaDelim(String[] args){
// return a Person instance UNSURE HERE
}
// make a toString method
public String toString()
{
String str = "person" + person + "age" + age + "city" + city;
return str;
}
}

Categories

Resources