how to add strings from different arrays into one array in java - 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]))}
}}

Related

java.lang.NullPointerException when I create an array that uses values of an other class

I have a class Student with 3 attributes,
public static class Student {
public String firstname;
public String lastname;
public int studentnumber;
}
that I want to initialize in an array in a suitable loop in an external class. The attributes of each student are to be initialized using user input (for that I have a Terminal class):
public class main {
public static void main(String[] args) {
int numberofstudents = Terminal.askInt("How many students to you want to enter? ");
Student[] array = new Student[numberofstudents];
for (int i = 0; i < numberofstudents; i++) {
array[i].firstname = Terminal.askString("Enter student's firstname ");
array[i].lastname = Terminal.askString("Enter student's lastname ");
array[i].studentnumbere = Terminal.askString("Enter student's number ");
}
}
}
But every time I initialize a value of the Array,
array[i].firstname = Terminal.askString("Student's firstname ");
I get the
Exception in thread "main" java.lang.NullPointerException
You need to initialize the array index with a new Student() before you can update the value at this array index. By default, Student[] contains null at each index and therefore you will get NullPointerException if you try to perform any operation (e.g. assigning a value to array[i].firstname) on it without initializing it will a non-null value.
for(int i = 0;i<numberofstudents;i++){
array[i] = new Student();
array[i].firstname = Terminal.askString("Enter student's firstname ");
array[i].lastname = Terminal.askString("Enter student's lastname ");
array[i].studentnumbere = Terminal.askString("Enter student's number ");
}
Your Student array is empty! It has a length of your input, but has no student objects in it.
Create a new Student, and add it to the list first!
for(int i = 0;i<numberofstudents;i++) {
array[i] = new Student();
array[i].firstname = Terminal.askString("Enter student's firstname ");
// ...
}
You need to initialize each items of an array with new Student();
It's better to have a normal Student class (NOT static one). It seems that you want to hold total student count number so you can only have that variable as a static attribute (private static int studentNumber), and whenever you create a new instance of Student just ++ the value of studentNumber. In this case you don't need to get students number each time.
And it's better to have private attributes and access them via getters and setters rather than public attributes.
public class Student {
private static int studentNumber = 0;
private String firstName;
private String lastName;
private Long studentId;
public Student(String firstName, String lastName, Long studentId) {
this.firstName = firstName;
this.lastName = lastName;
this.studentId = studentId;
studentNumber++; // increase students count after each initialization
}
public static int getStudentNumber() {
return studentNumber;
}
public static void setStudentNumber(int studentNumber) {
Student.studentNumber = studentNumber;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Long getStudentId() {
return studentId;
}
public void setStudentId(Long studentId) {
this.studentId = studentId;
}
}
In your Main class, you need to initialize each items of an array with new Student();
public class Main {
public static void main(String[] args) {
int numberOfStudents = Terminal.askInt("How many students to you want to enter? ");
// this line just create an empty array that can hold Student objcets in it
Student[] array = new Student[numberOfStudents];
for (int i = 0; i < array.length; i++) {
// you need to initialize each items of an array with new()
array[i] = new Student(Terminal.askString("Enter student's firstname "),
Terminal.askString("Enter student's lastname "),
Terminal.askString("Enter student's ID "));
}
}
}
Don't forget to follow indentation rules, and start all classes name with Uppercase (Main, Student, Terminal, etc.). Finally use camel-case (studentNumbers, firstName, lastName).
You can add a constructor with three fields to the Student class and simplify your code as follows:
public static class Student {
public String firstname;
public String lastname;
public int studentNumber;
public Student(String firstname, String lastname, int studentNumber) {
this.firstname = firstname;
this.lastname = lastname;
this.studentNumber = studentNumber;
}
}
public static void main(String[] args) {
int numberOfStudents =
Terminal.askInt("How many students to you want to enter? ");
Student[] array = new Student[numberOfStudents];
for (int i = 0; i < numberOfStudents; i++) {
array[i] = new Student(
Terminal.askString("Enter student's firstname "),
Terminal.askString("Enter student's lastname "),
Terminal.askString("Enter student's number "));
}
}

How to write a method that reads particular content in an array lists and count the number of array's content

I am a new learner and I should create a method that will make this program work with no problems at all so I can get the :::final result that should look like this:::
3 is 3
Mark is Mark
Richard is Richard
Here is the code (PLEASE read the comments I wrote in the code)
public class Main {
/*I wrote the following method (Student) but I keep get some issues:
Please help I spend many days and I can't figure it out and I am runnung out
of time as I should understand the problem or at least the correction that I
can read and figure out what I was doing wrong.*/
// My written code starts here
public static String Student(String[] sx){
int counter = 0;
for (int i = 0; i < sx.length; i ++){
if (sx[i] != null) counter ++;
}
return counter;
sx = new String[counter];
}
// My written code ENDS here
// From this point I should preserve the code without any changes
static Student studentA;
static Student studentB;
static Student studentC;
public static void main(String[] args) {
studentA = new Student("Mark", "John", "Jimmy");
studentB = new Student("Will", "George", "Androw");
studentC = new Student("Frank", "Sam");
int totalStudents = Student.getTotalStudents();
System.out.println(totalStudents + " is 3");
System.out.println(studentA.getFirstName() + " is Mark");
studentA.setFirstName("Richard");
System.out.println(studentA.getFirstName() + " is Richard");
}
}
Check the following code snippet
import java.util.List;
public class Main {
// My written code starts here
static class Student {
String firstName;
String middleName;
String lastName;
// Constructor for setting the class variable with all 3 field
public Student(String firstName, String middleName, String lastName) {
this.firstName = firstName;
this.middleName = middleName;
this.lastName = lastName;
}
// Constructor for setting the class variable with 2 field
public Student(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
//to get the FirstName field of a student object
public String getFirstName() {
return firstName;
}
//to set the FirstName field of a student object
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public static int getTotalStudents() {
// this is wrong way of doing this.
// You should ideally send a list Of Student to know the number of students as shown below
return 3;
}
public static int getTotalStudentsFromList(List<Student> studentList) {
return studentList.size();
}
}
// My written code ENDS here
// From this point I should preserve the code without any changes
static Student studentA;
static Student studentB;
static Student studentC;
public static void main(String[] args) {
studentA = new Student("Mark", "John", "Jimmy");
studentB = new Student("Will", "George", "Androw");
studentC = new Student("Frank", "Sam");
int totalStudents = Student.getTotalStudents();
System.out.println(totalStudents + " is 3");
System.out.println(studentA.getFirstName() + " is Mark");
studentA.setFirstName("Richard");
System.out.println(studentA.getFirstName() + " is Richard");
}
}
I have added possible comments to explain the code. Let me know if you feel any difficulty in understanding this.

Create method to count occurrences of type char within an array

I need to create a method that searches a String array whether a specfic character exists in the array and returns an integer of the number of occurrences the character appears, I have looked on other posts to try and work it out myself but they are all arrays of int not String
I have another class name hence the array name being type Name.
public class Reg {
//Fields
private ArrayList<Name> Name;
//Constructors
public Reg() {
Name = new ArrayList<>();
}
//Methods
public int CountCharacterOccurrences (Char character){
}
}
Name Class:
public class Name implements Comparable<Name> {
//Fields
private String firstName;
private String familyName;
//Constructors
public Name() {
firstName = "";
familyName = "";
}
public Name(String firstName, String familyName) {
this.firstName = firstName;
this.familyName = familyName;
}
//Methods
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setFamilyName(String familyName) {
this.familyName = familyName;
}
public String getFirstName() {
return firstName;
}
public String getFamilyName() {
return familyName;
}
public String getFullName() {
if (firstName.equals("") && familyName.equals("")) {
return "";
} else {
return firstName + " " + familyName;
}
}
#Override
public String toString() {
return "Name:[firstName=" + firstName + ", familyName=" + familyName + "]";
}
}
How do I add a method CountCharacterOccurences that accepts a char argument and returns an int signalling the number of occurrences.
Maybe this is what you mean:
class Reg{
private ArrayList<Name> names;
public Reg() {
names = new ArrayList<>();
}
public int countFirstNameOccurrences(char c) {
return names.stream() // get Stream<Name>
.map(Name::getFirstName) // convert Stream<Name> to Stream<String> using Name's firstName
.mapToInt(s -> s.length() - s.replace(String.valueOf(c), "").length()) // calculate every occurrence c in each firstName and get an IntStream
.sum(); // sum all the values
}
public static void main(String[] args) {
Reg reg = new Reg();
reg.names.add(new Name("John", "Doe"));
reg.names.add(new Name("Johnny ", "Doe"));
reg.names.add(new Name("Richard", "Roe"));
reg.names.add(new Name("James", "Roe"));
reg.names.add(new Name("Jane", "Roe"));
System.out.println(reg.countFirstNameOccurrences('J'));
}
}
Output:
4
as there are 4 J's in the first names in the list (John, Johnny, James and Jane)

How to add a object to a sorted set that's within a hashmap of objects

I'm trying to add a passenger object into a sorted set. This sorted set is in a cruise object. All of the cruise objects are within a hashMap. I'm kinda new to collections so I'm having trouble. This is my attempt to do what I'm doing.
HashMap<String, Cruise> cruiseMap = new HashMap<String, Cruise>();
SortedSet<Passenger> passengerSet = new TreeSet<Passenger>();
Queue<Passenger> waitingList = new LinkedList<Passenger>();
Cruise cruise = new Cruise("1", passengerSet, waitingList, false);
cruiseMap.put("1", cruise);
Passenger passenger = new Passenger("Smith", "J");
cruiseMap.get("1").getPassengerSet().add(passenger);
The passenger's parameters are strings that are last name then their first initial. The cruise's parameters are as a string the date, the sortedSet passengers, there's a queue for waiting list and a boolean variable to determine if the ship has departed. I keep getting tons of errors when I run this code. Thanks in advance for the help.
Here are the errors I'm recieving.
Exception in thread "main" java.lang.ClassCastException: edu.ilstu.Passenger cannot be cast to java.lang.Comparable
at java.util.TreeMap.compare(Unknown Source)
at java.util.TreeMap.put(Unknown Source)
at java.util.TreeSet.add(Unknown Source)
at edu.ilstu.Driver.main(Driver.java:48)
Passenger Class
public class Passenger {
private String lastName = "";
private String firstName = "";
public Passenger()
{
lastName = "no last name yet";
firstName = "no first name yet";
}
public Passenger(String lastName, String firstName)
{
this.lastName = lastName;
this.firstName = firstName;
}
/**
* #return the lastName
*/
public String getLastName()
{
return lastName;
}
/**
* #param lastName the lastName to set
*/
public void setLastName(String lastName)
{
this.lastName = lastName;
}
/**
* #return the firstName
*/
public String getFirstName()
{
return firstName;
}
/**
* #param firstName the firstName to set
*/
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
/* (non-Javadoc)
* #see java.lang.Object#toString()
*/
#Override
public String toString()
{
return lastName + " " + firstName;
}
}
Cruise Class
public class Cruise
{
private String day = "";
private SortedSet<Passenger> passengerSet = new TreeSet<Passenger>();
private Queue<Passenger> waitingList = new LinkedList<Passenger>();
private boolean hasDeparted = false;
public Cruise()
{
day = "no day yet";
passengerSet = null;
waitingList = null;
hasDeparted = false;
}
public Cruise(String day, SortedSet<Passenger> passengerSet, Queue<Passenger> waitingList, boolean hasDeparted)
{
this.day = day;
this.passengerSet = passengerSet;
this.waitingList = waitingList;
this.hasDeparted = hasDeparted;
}
/**
* #return the day
*/
public String getDay()
{
return day;
}
/**
* #param day the day to set
*/
public void setDay(String day)
{
this.day = day;
}
/**
* #return the passengerSet
*/
public SortedSet<Passenger> getPassengerSet()
{
return passengerSet;
}
/**
* #param passengerSet the passengerSet to set
*/
public void setPassengerSet(SortedSet<Passenger> passengerSet)
{
this.passengerSet = passengerSet;
}
/**
* #return the waitingList
*/
public Queue<Passenger> getWaitingList()
{
return waitingList;
}
/**
* #param waitingList the waitingList to set
*/
public void setWaitingList(Queue<Passenger> waitingList)
{
this.waitingList = waitingList;
}
/**
* #return the hasDeparted
*/
public boolean isHasDeparted()
{
return hasDeparted;
}
/**
* #param hasDeparted the hasDeparted to set
*/
public void setHasDeparted(boolean hasDeparted)
{
this.hasDeparted = hasDeparted;
}
}
It happens because your passengerSet is TreeSet (SortedSet), which means it will sort itself after each adding, because TreeSet is ordered set and has certain sequence unlike usual HashMap. Every SortedMap must know how to sort elements it contains. This can be done two ways:
You can implement your class from Comparable<T> interface.
You can add custom Comparator<T> to your SortedMap.
So, you have three ways to fix it (may be more, but three of them - are obvious):
Get rid of SortedMap, let's say replace your SortedMap to Map and replace TreeMap to HashMap in your code.
Add custom comparator to your passengerSet
HashMap<String, Cruise> cruiseMap = new HashMap<String, Cruise>();
SortedSet<Passenger> passengerSet = new TreeSet<Passenger>(new Comparator<Passenger>() {
#Override
public int compare(Passenger lhs, Passenger rhs) {
return lhs.getFirstName().compareTo(rhs.getFirstName());
}
});
Queue<Passenger> waitingList = new LinkedList<>();
Cruise cruise = new Cruise("1", passengerSet, waitingList, false);
cruiseMap.put("1", cruise);
Passenger passenger = new Passenger("Smith", "J");
cruiseMap.get("1").getPassengerSet().add(passenger);
Implement the Comparable<T> interface in your Passenger class.
public class Passenger implements Comparable<Passenger> {
private String lastName = "";
private String firstName = "";
public Passenger()
{
lastName = "no last name yet";
firstName = "no first name yet";
}
public Passenger(String lastName, String firstName)
{
this.lastName = lastName;
this.firstName = firstName;
}
/**
* #return the lastName
*/
public String getLastName()
{
return lastName;
}
/**
* #param lastName the lastName to set
*/
public void setLastName(String lastName)
{
this.lastName = lastName;
}
/**
* #return the firstName
*/
public String getFirstName()
{
return firstName;
}
/**
* #param firstName the firstName to set
*/
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
/* (non-Javadoc)
* #see java.lang.Object#toString()
*/
#Override
public String toString()
{
return lastName + " " + firstName;
}
#Override
public int compareTo(Passenger another) {
return firstName.compareTo(another.firstName);
}
}

Java ClassCastException error with Comparable interface despite implementation

I'm working on a class assignment that accepts last name, first name and score for one or more students, stores them in an array and then sorts alphabetically by last name (or first name if last name is the same).
We're required to use a Student class that implements the Comparable interface.
As soon as I get to the Arrays.sort portion of the code, I get a ClassCastException stating that "Student cannot be cast to java.lang.Comparable".
I've searched and reviewed, tried to use implements Comparable<Student>, Clean and Build, but the error persists. Any help or hints are appreciated.
the error:
Exception in thread "main" java.lang.ClassCastException:
studentscoreapp.Student cannot be cast to java.lang.Comparable
at java.util.Arrays.mergeSort(Arrays.java:1144)
at java.util.Arrays.sort(Arrays.java:1079)
at studentscoreapp.StudentScoreApp.main(StudentScoreApp.java:35)
Java Result: 1 BUILD SUCCESSFUL (total time: 12 seconds)
Here's my Student class:
public class Student implements Comparable
{
private String lastName;
private String firstName;
private int score;
public Student(String fName, String lName, int s)
{
fName = firstName;
lName = lastName;
s = score;
}
public String getLastName()
{
return lastName;
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
public String getFirstName()
{
return firstName;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public int getScore()
{
return score;
}
public void setScore(int score)
{
this.score = score;
}
#Override
public int compareTo(Object obj)
{
Student sent = (Student) obj;
if (sent.lastName.equals(this.lastName))
{
return this.firstName.compareToIgnoreCase(sent.firstName);
}
else return this.lastName.compareToIgnoreCase(sent.lastName);
}
#Override
public String toString()
{
return lastName + firstName + score;
}
}
the Comparable interface:
public interface Comparable
{
int compareTo(Object obj);
}
and my main:
import java.util.Arrays;
public class StudentScoreApp
{
public static void main(String[] args)
{
String firstName;
String lastName;
int score;
System.out.println("Welcome to the Student Scores Application");
int numStudents = Validation.getInt("Enter # of Students: ");
Student[] studentArray = new Student[numStudents];
int i;
for (i = 0; i < numStudents; i++)
{
firstName = Validation.getString("Student [" + (i + 1) + "] first name: ");
lastName = Validation.getString("Student [" + (i + 1) + "] last name: ");
score = Validation.getInt("Student [" + (i + 1) + "] score: ", 0, 100);
studentArray[i] = new Student(firstName, lastName, score);
}
Arrays.sort(studentArray); //line 35
System.out.println();
//take each obj of the array and print the student info
for (Student obj : studentArray)
{
System.out.println(obj.toString());
}
}
}
Arrays.sort() accepts an array of objects which are subtypes of java.lang.Comparable. In your code, you have created your own Comparable interface, which, while it behaves the same way as java.lang.Comparable, is not the same interface.

Categories

Resources