I want to solve this problem without using arraylist.
i want to add the contact to its specific index in the array of strings. And then display all the added contacts in string format seperated by commas.
My code gives the result of only last added contract:
Contact [first=Bob, last=Moore, number=555-9756]
where is the problem in my code?
Is there any idea how to solve???
This class consist of the main method:
This is the main class:
public class ExampleApp {
public static void main(String[] args) {
PhoneBook pb = new PhoneBook("Personal book");
System.out.println( pb.getName() );
pb.add("Alice", "Green", "555-1234");
pb.add("Mary", "Smith", "555-6784");
pb.add("Bob", "Moore", "555-9756");
System.out.println( pb.toString() );// here i want to display all the contracts seperated by commas
System.out.println( pb.first() );// first contract
System.out.println( pb.get(2) );// second contract
String toBeFound = new String("Moore");
System.out.println( pb.find(toBeFound) );// display the found contract
}
}
This is the phonebook class:
public class PhoneBook {
public static final int MAX = 10;
public String name;
String[] contracts = new String[MAX]; // i created an array of strings
Contact c;
/**
* Create a new phonebook with given name
*/
public PhoneBook(String name) {
this.name = name;
}
/**
* Return the phonebook name
*/
public String getName() {
return name;
}
/**
* Insert a new contact at the end
*/
public void add(String first, String last, String number){
c=new Contact(first,last,number);
for(int i=0;i<MAX;i++){ // i added for each array index the contracts strings
contracts[i]= c.toString();
}
}
/**
* Return the first contact
*/
public String first() {
return get(1);
}
/**
* Return the i-th contact (supposing that first
* index is 1)
*/
public String get(int i) {
String s =contracts[i].toString();
return s;
}
/**
* Return a string containing the list of textual
* representation of all contacts, separated by ", ".
* List starts with "("and ends with ")"
*/
public String toString() {
String s= " ";
for(int i=1;i<MAX;i++){ // here i tried to display the string looping the array
s=contracts[i].toString();
}
return s;
}
/**
* Return the textual representation of first
* contact containing "needle"
*/
public String find(String needle) {
//TODO: to be implemented
return null;
}
}
This is the contact class :
public class Contact {
public String first;
public String last;
public String number;
public String[] contacts;
public Contact(String first, String last, String number) {
this.first=first;
this.last = last;
this.number=number;
}
public String getFirst() {
return first;
}
public void setFirst(String first) {
this.first = first;
}
public String getLast() {
return last;
}
public void setLast(String last) {
this.last = last;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
#Override
public String toString() {
return "Contact [first=" + first + ", last=" + last + ", number="
+ number + "]";
}
}
You can use ArrayList for it. It will help you really much and you should make your veriables private.
private String first;
private String last;
private String number;
private ArrayList<String> list = new ArrayList<String>();
for(String pointer : list){
}
or you can make contact saver ArrayList
private ArrayList<Contact> list = new ArrayList<Contact>();
public Contact(String first, String last, String number) {
this.first=first;
this.last = last;
this.number=number;
}
public void add(String first, String last, String number){
c=new Contact(first,last,number);
list.add(c);
}
and you can access all veriables like that list.get(i).first.
You can save your contact class and contracts array in arraylist and it will give you more power to access. If you want to display your ArrayList, which index is not important, you need only ++i for it.
I changed your class look this:
public class PhoneBook {
public static final int MAX = 10;
public String name;
String[] contracts = new String[MAX]; // i created an array of strings
Contact c;
private int count = 0;// saved last index of array
public PhoneBook(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void add(String first, String last, String number) {
c = new Contact(first, last, number);
contracts[count] = c.toString(); // save your String inside of last index++
count++;
}
public String first() {
return get(1);
}
public String get(int i) {
String s = contracts[i].toString();
return s;
}
public String toString() {
for (int i = 0; i < MAX; i++) {
if (contracts[i] != null)
System.out.println(contracts[i].toString());
}
return "";
}
public String find(String needle) {
return null;
}
}
public class Contact {
public String first;
public String last;
public String number;
public Contact(String first, String last, String number) {
this.first = first;
this.last = last;
this.number = number;
}
#Override
public String toString() {
return "Contact [first=" + first + ", last=" + last + ", number="
+ number + "]";
}
}
//Personal book
//Contact [first=Alice, last=Green, number=555-1234]
//Contact[first=Mary, last=Smith, number=555-6784]
//Contact [first=Bob, last=Moore, number=555-9756]
you always delete your last toString method. Your Add method is wrong. You always turn 0 and write again inside of array.
You should keep track of the last contact added to your array :
private int lastIndex = 0; // index of first available index of the array
...
/**
* Insert a new contact at the end
*/
public void add(String first, String last, String number){
c=new Contact(first,last,number);
if (lastIndex < MAX)
contracts[lastIndex++]= c.toString();
}
Some other issues with your code :
/**
* Return the first contact
*/
public String first() {
return get(1); // should be get(0)
}
Calling toString() for contracts[i] is redundant, since it's already a String. Perhaps you meant to store Contact instances instead of Strings in your array? That would make more sense.
Add an extra variable static int Last = 0; To track how many contact you have added and update the add function as .
public void add(String first, String last, String number){
if(Last>=MAX){
System.out.println("Error in adding\n");
}
else{
c=new Contact(first,last,number);
contacts[Last] = c.toString();
Last++;
}
}
Change Tostring() for loop to last. So that you will be printing only added contact .In your case you are printing upto MAX that is wrong when less no of contacts are added.
You have to pass i=0,1,2,...,MAX-1 to get(i) function . Array is Zero(0) based indexed.
So, the problem you are having is that you always retrieve the last contact, regardless of which one you try to get. This is because when you add a new contact, you are actually replacing ALL the contacts, making them all the same. You are getting the correct contact from the phonebook, but they ALL have the same value.
To fix it, do the following:
public class PhoneBook
{
int contactsAdded = 0; // Add an integer to store how many contacts you have added
Contact[] contacts = new Contact[MAX]; //Change this to Contact array, not string
//Contact c; //You can remove this line
//Rest of your code
}
public void add(String first, String last, String number)
{
//Only add if the number of contacts is less than the max
if (contactsAdded < MAX)
{
//Construct the new contact when you use it.
contacts[contactsAdded] = new Contact(first, last, number);
contactsAdded++;
}
}
Not sure if I understood all of your code right, but I think you are overwriting all other contacts in your phone book:
public void add(String first, String last, String number){
c=new Contact(first,last,number); //(1)
for(int i=0;i<MAX;i++){ //(2)
contracts[i]= c.toString();
}
}
At position (1) a new Contact object is created and assigned to c. In the next step (2), you loop through the array and assign the info contained in c (the latest contact added) to all already entries in the contracts array.
Independent from your problem, I suggest that you replace the array of a fixed size with i.e. an ArrayList of type Contact. Adding entries to this list, iterating, sorting etc is very easy.
Related
I am trying to call the array variables in the reference class, try to sort them using a user-defined method and call the method onto the case statement that will be invoked if the user chooses a particular number. I wanted to provide the user the option what attribute of a student will be sorted (i.e. name, course...) and show the sorted one dimensional array called in the case statements and invoked through the main method.
Here's the variables in the Reference class:
class RecordReference {
private int idNumber;
private String firstName = "";
private String middleName = "";
private String lastName = "";
private int age;
private String yearLevel;
private String course = "";
private double gwa;
public RecordReference(int i, String f, String m, String l, int a, String y, String c, double g) {
idNumber = i;
firstName = f;
middleName = m;
lastName = l;
age = a;
yearLevel = y;
course = c;
gwa = g;
}
public int getIdNumber() {
return idNumber;
}
public String getFirstName() {
return firstName;
}
public String getMiddleName() {
return middleName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
public String getYearLevel() {
return yearLevel;
}
public String getCourse() {
return course;
}
public double getGwa() {
return gwa;
}
public void setIdNumber(int idnumber) {
idNumber = idnumber;
}
public void setFirstName(String fName) {
firstName = fName;
}
public void setMiddleName(String mName) {
middleName= mName;
}
public void setLastNameName(String lName) {
lastName= lName;
}
public void setAge(int a) {
age = a;
}
public void setYearLevel(String yLevel) {
yearLevel = yLevel;
}
public void setCourse(String c) {
course = c;
}
public void setGwa(int gwa) {
gwa = gwa;
}
public String toString() {
return String.valueOf(System.out.printf("%-15s%-15s%-15d%-15d%n",
firstName, course , yearLevel ,gwa));
}
} // end of class
And I am trying to call it in this sort method, but I don't know how to reference it.
public static void sortFirstNameArray(String[] f){
for (int i = 0; i < f.length - 1; i++) {
for (int j = i + 1; j < f.length; j++) {
if (f[i].compareToIgnoreCase(f[j]) > 0) {
String temp = f[i];
f[i] = f[j];
f[j] = temp;
}
}
}
}
After the sorting is successfully done, I'll call it in a switch case statements that will be invoked once the user chooses a particular number. This part has 5 case statements (Name, Age, Course, General Weighted Average and the option to sort it all - I plan to add more student attributes if this works)
(I don't know if I should store this in another method and call it in the main method or just put it in the main method like that)
public RecordReference Process(RecordReference[] f, RecordReference[] a) {
// for loop?
for (int x = 0; x < f.length; x++) {
switch (choice) {
case 1:
System.out.println("Sorted array of first name: ");
sortFirstNameArray(f[x].getFirstName());
System.out.printf("%-15s%n", Arrays.toString(f));
break;
case 2:
System.out.println("Sorted array of age: ");
// invokes the age method
sortAgeArray(a[x].getAge());
System.out.printf("%-15s%n", Arrays.toString(a));
break;
}
}
}
If it is in another method, what param do I include when I call it in the main method?
I tried this but it doesn't work, I don't know what to do
System.out.print("Please choose what student attribute you want to
sort :");
choice = keyboard.nextInt();
// calling the process method here, but I receive syntax error
Process(f,a); // Here, I want to pass the sorted values back into the array but I get an error.
If you can help me out that would be great. Thank you in advance.
I'm just a first year student and I am eager to learn in solving this error.
It's good to see that you have attempted the problem yourself and corrected your question to make it clearer, because of that I am willing to help out.
I have tried to keep the solution to the problem as close to your solution as possible, so that you are able to understand it. There may be better ways of solving this problem but that is not the focus here.
First of all, let's create a class named BubbleSorter that will hold methods for sorting:
public class BubbleSorter
{
//Explicitly provide an empty constructor for good practice.
public BubbleSorter(){}
//Method that accepts a variable of type RecordReference[], sorts the
//Array based on the firstName variable within each RecordReference
//and returns a sorted RecordReference[].
public RecordReference[] SortByFirstName(RecordReference[] recordReferencesList)
{
for (int i = 0; i < recordReferencesList.length - 1; i++) {
for (int j = i + 1; j < recordReferencesList.length; j++) {
if (recordReferencesList[i].getFirstName().compareToIgnoreCase
(recordReferencesList[j].getFirstName()) > 0) {
RecordReference temp = recordReferencesList[i];
recordReferencesList[i] = recordReferencesList[j];
recordReferencesList[j] = temp;
}
}
}
return recordReferencesList;
}
}
That gives us a class that we can instantiate, where methods can be added to be used for sorting. I have added one of those methods which takes a RecordReference[] as a parameter and sorts the RecordReference[] based on the firstName class variable within each RecordReference. You will need to add more of your own methods for sorting other class variables.
Now for the main class:
class Main {
public static void main(String[] args) {
//Get a mock array from the GetMockArray() function.
RecordReference[] refArray = GetMockArray();
//Instantiate an instance of BubbleSorter.
BubbleSorter sorter = new BubbleSorter();
//Invoke the SortByFirstName method contained within the BubbleSorter
//and store the sorted array in a variable of type RecordReference[] named
//sortedResult.
RecordReference[] sortedResult = sorter.SortByFirstName(refArray);
//Print out the results in the sorted array to check if they are in the correct
//order.
//This for loop is not required and is just so that we can see within the
//console what order the objects in the sortedResult are in.
for(int i = 0; i < sortedResult.length; i++)
{
System.out.println(sortedResult[i].getFirstName());
}
}
public static RecordReference[] GetMockArray()
{
//Instantiate a few RecordReferences with a different parameter for
//the firstName in each reference.
RecordReference ref1 = new RecordReference(0, "Ada", "Test", "Test", 22, "First",
"Computer Science", 1.0f);
RecordReference ref2 = new RecordReference(0, "Bob", "Test", "Test", 22, "First",
"Computer Science", 1.0f);
RecordReference ref3 = new RecordReference(0, "David", "Test", "Test", 22,
"First", "Computer Science", 1.0f);
//Create a variable of type RecordReference[] and add the RecordReferences
//Instantiated above in the wrong order alphabetically (Based on their firstName)
//class variables.
RecordReference[] refArray = {
ref2, ref3, ref1
};
return refArray;
}
}
In the main class I have provided verbose comments to explain exactly what is happening. One thing I would like to point out is that I have added a method named GetMockArray(). This is just in place to provide a RecordReference[] for testing and you probably want to do that somewhere else of your choosing.
If anything is not clear or you need some more assistance then just comment on this answer and I will try to help you further.
Thanks.
I am relatively new to programming and an working with setters and getters at the moment.
I have something set up where I have a student class that has information about said student, including their first, middle, and last name, their student ID, and their major.
I need to set it so that, if their student ID is less than zero, it automatically sets it to -1. I also need to set the major to undecided if they do not input anything.
I also need to override the toString method and print all of this information out.
I feel like I have the first part with the names down, I am not sure about the rest of it however. I am not sure how I am supposed to use the toString method while also using setters and getters.
Below is my Student class that does all of the work.
import java.util.Objects;
import java.util.Scanner;
public class Student {
String first;
String middle;
String last;
String major = "Undecided";
static int studentID = -1;
public Student(String first, String middle, String last) {
Objects.requireNonNull(first);
Objects.requireNonNull(last);
}
public void setFirst(String A) {
first = A;
}
public void setMiddle(String B) {
middle = B;
}
public void setLast(String C) {
last = C;
}
private String getFirst() {
return first;
}
private String getMiddle() {
return middle;
}
private String getLast() {
return last;
}
private String getMajor() {
return major;
}
public void setMajor(){
static void register(int a){
if (a < 0) {
studentID = a;
} else {
studentID = getID(a);
}
}
private static int getID(int a) {
if (studentIDInput < 0) {
studentID = -1;
} else {
studentID = a;
}
return studentID;
}
public static void main(String[] args) {
String first = "abc";
String middle = "def";
String last = "ghi";
Scanner sc = new Scanner(System.in);
String majorInput = sc.next();
int studentIDInput = sc.nextInt();
Student student1 = new Student(first, middle, last);
System.out.println(student1.getFirst().toString() + " " + student1.getMiddle().toString() + " " + student1.getLast().toString() + '\n' + "Major:" + " " + student1.getMajor().toString() + '\n' );
}
#Override
public String toString() {
return ;
}
}
I have also included the Driver class just for reference.
public class Driver {
static String first;
static String middle;
static String last;
public static void main(String[] args){
Student student1 = new Student(first, middle, last);
student1.setFirst("Mikayla");
student1.setMiddle("Rose");
student1.setLast("Knox");
}
}
You have this constructor:
public Student(String first, String middle, String last) {
Objects.requireNonNull(first);
Objects.requireNonNull(last);
}
It does its job of checking that first and last name are not null, but it does not do anything with the values besides checking. The constructor's job is to construct the object, i.e, initialize its member variables. When your constructor is done, you should have a usable object, without having to call any setters in it.
You need to add that:
public Student(String first, String middle, String last) {
Objects.requireNonNull(first);
Objects.requireNonNull(last);
this.first = first;
this.middle = middle;
this.last = last;
}
Note that you don't need to use setters here as code within the class can access member variables directly. You can use setters if you want, though.
As for toString: this is a method mainly used in debugging, and it displays some helpful information about the object it's called on. You could implement it like below, with a bit of ?: to make sure to only print the middle name if it's not null:
#Override
public String toString() {
return first + " " + (middle != null ? middle + " " : "") + last;
}
I'll leave it to you to also include major and ID.
On using a Scanner: You use a Scanner to get input from somewhere, like the from the user. You don't need it in toString or any setters or getters. These are all methods that should be very simple and not deal with I/O classes like Scanner.
If you are using constructors, you do not really need setters. Try something like this:
class Student {
private String first;
private String middle;
private String last;
private String major;
private int studentID;
public Student(String first, String middle, String last) {
this(first, middle, last, "undecided", -1);
}
public Student(String first, String middle, String last, String major, int studentID) {
this.first = first;
this.middle = middle;
this.last = last;
this.major = major;
this.studentID = studentID;
}
#Override
public String toString() {
return "first: " + first + "\nmiddle: " + middle + "\nlast: " + last + "\nmajor: " + major + "\nid: " _ studentID;
}
}
This way, when you create a new Student object with 3 parameters, the last 2 are automatically set to "undecided" and -1. If there is a case when you have the ID and not the major (or the other way around), you can add more constructors.
The program is supposed to assign random values to the Student objects in the studentArr array.
Right now it is only printing out null values. Ive tried several different print methods.
I'm pretty sure its something wrong with either my method that is supposed to fill out each student object's attributes, or with my print statement.
import java.util.*;
public class Lab6Excercise
{
String[] first={"Rick","Morty","Moriarty","Samus","Promethius","Geiger","Moriarti","Bob","Taco",
"Asparagus","Shoes","Potato","Dirty","Dan","Spongebob","Space","Nova","Illadin","Orange","Electron"};
String[] last={"PoopyButthole","Red","Mantis","Toboggan","Oak","Elm","Dumbledore","Potter","Spice","Toothbrush","Argon",
"Blitz","LazerWolf","Mc-BigMac","King","Queen","Spork","Petrolium","Apple","Trash"};
//no syntax errors if set to static, but prints out null for everything.
//problem here or in calling array to print?
public static Student[] studentArr= new Student[20];
public Lab6Excercise(){
initializeArray();
}
public void initializeArray(){
for(int i=0; i>20; i++){
//this one seems correct but it cant find the symbol method- setStudentID etc. methods
// online it said to try (Student)studentArr.setStudentID(id())
//which explicitely casts it
//seems to work
//http://stackoverflow.com/questions/29328569/setting-values-to-an-array-of-objects
studentArr[i]= new Student();
studentArr[i].setStudentID(id());
studentArr[i].setFirstName(First());
studentArr[i].setLastName(Last());
studentArr[i].setGrade(Grades());
//other way?probably wrong
//studentArr[i]= new Student(studentArr.id(),
//studentArr.First(),
//studentArr.Last(),
//studentArr.Grades());
}
}
public Student[] getStudentArr(){
return studentArr;
}
//do i even need this?
//public Lab6Excercise getLab(){
// return lab;
//}
public static void main(String[] args){
//randomly generate double grade, student id;
//create 2 arrays, first name, last name. pull randomly for name generation
//necessary? how do i
Lab6Excercise lab= new Lab6Excercise();
//prints out hash or something
//System.out.println(lab.studentArr.toString());
//prints out nulls
// System.out.println(Arrays.deepToString(studentArr));
for(int i=0; i<studentArr.length; i++){
System.out.println(studentArr[i]);
}
}
public int id(){
int ID=1+(int)(Math.random()*((100-1)+1));
return ID;
}
public String First(){
Random random= new Random();
int index= random.nextInt(first.length);
return first[index];
}
public String Last(){
Random random= new Random();
int index= random.nextInt(last.length);
return last[index];
}
public double Grades(){
double grade=0+(double)(Math.random()*((4-1)+1));
return grade;
}
}
and the object class
import java.util.Random;
public class Student
{
private int studentID;
private String firstName;
private String lastName;
private double grade;
// no-argument constructor calls other constructor with default values
public Student()
{
this( 0, "", "", 0.0 ); // call four-argument constructor
} // end no-argument Student constructor
// initialize a record
public Student( int id, String first, String last, double grade )
{
setStudentID( id );
setFirstName( first );
setLastName( last );
setGrade( grade );
} // end four-argument Student constructor
// set student ID number
public void setStudentID( int id )
{
studentID = id;
} // end method setStudentID
// get student ID number
public int getStudentID()
{
return studentID;
} // end method getStudentID
// set first name
public void setFirstName( String first )
{
firstName = first;
} // end method setFirstName
// get first name
public String getFirstName()
{
return firstName;
} // end method getFirstName
// set last name
public void setLastName( String last )
{
lastName = last;
} // end method setLastName
// get last name
public String getLastName()
{
return lastName;
} // end method getLastName
// set grade
public void setGrade( double gradeValue )
{
grade = gradeValue;
} // end method setGrade
// get grade
public double getGrade()
{
return grade;
} // end method getGrade
public static int getRandom(int[] array){
int rnd= new Random().nextInt(array.length);
return array[rnd];
}
public String toString(){
return "First name: "+firstName + "Last name: " + lastName+ "ID: "+ studentID+ "Grade: " + grade+"\n";
}
}
You never initialize your array, because your for loop indexing is wrong.
for (int i = 0; i > 20; i++)
This says: for i starting at 0, run the following code if i is greater than 20, incrementing the value of i by 1 each time. Since i starts out already being less than 20, it is never greater than 20, and the code never runs. Instead, do the following, making your run-condition i less than 20:
for (int i = 0; i < 20; i++)
Or, better yet:
for (int i = 0; i < studentArr.length; i++)
For more details on the syntax of the for statement, check out the Java documentation.
It's a simple error in your for loop in the initialize array method. The statement: i >20 is the condition under which the loop will execute. But if i starts as 0 it will never be 20 and the loop will never execute. Just change the condition (which is i >20 right now) to i < 20 and it will work. :)
i'm in need of assistance with a small error in my code. I have a program that has 4 String Arrays that i have to combine and print in separate places using constructors. I need to write a method: Employee[] searchWithId(Employee[] list, String search) which searches for a string in the array and returns the matched string along with the other corresponding information.
For example:
searchWithId(list, "P102432"); // search the list for the given id
Output:
Searching for the id number:P102432 ...
Found the record for the id number:P102432
first name:Amber Last Name:Nogofski
Id number:P102432
Employee number:No employee number has been assigned yet!
Heres my code so far:
Employee Class:
public static 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!\n";
}
return result + getEmployeeNumber() + "\n";
}
}
My main and other methods:
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"};
Employee[] list = new Employee[firstNames.length];
list = listOfEmployees(firstNames, lastNames, idNumbers); // create the list of employees in one array
System.out.println("List of employees before sorting...\n");
printEmployeeList(list); //print the list of employees
System.out.println(); // new line
searchWithId(list, "P102432"); // search the list for the given id
searchWithLastName(list, "Bond"); // search the list for the given last name
System.out.println(); // new line
searchWithId(list, "P1024444"); // search the list for the given id
searchWithLastName(list, "BoNd"); // search the list for the given last name
System.out.println();// new line
sortWithFirstName(list); // sort the employee list and then call appropriate method to print it.
list = assignEmployeeNum(list, employeeNum); // assign the employee number to the employees
System.out.println("+++After adding the employee number to the list+++");// new line
printEmployeeList(list); // print the list again with the employee number
searchWithEmployeeNum(list, "5555"); // search the list for the given employee number
sortWithFirstName(list); // sort the employee list and then call appropriate method to print it.
}
public static Employee[] listOfEmployees(String[] firstName, String[] lastName, String[] idNumber) {
Employee[] list = new Employee[firstName.length];
for (int i = 0; i < list.length; i++) {
list[i] = new Employee(firstName[i], lastName[i], idNumber[i]);
}
return list;
}
public static void printEmployeeList(Employee[] list) {
Arrays.stream(list).forEach(System.out::println);
}
public static Employee[] searchWithId(Employee[] list, String search) {
System.out.println("Searching for the id number: " + search);
for (int i = 0; i < list.length; i++) {
if (list[i].getIdNumber().equals(search)) {
System.out.println("Found id number: " + search);
//Arrays.toString(list); <- my try
}
}
return list;
}
You can do it as follows:
import java.util.Arrays;
public static Employee[] searchWithId(Employee[] list, String search) {
System.out.println("Searching for the id number: " + search);
Employee[] filteredEmployees = new Employee[list.length];
int index = 0;
for (int i = 0; i < list.length; i++) {
if (list[i].getIdNumber().equalsIgnoreCase(search)) {
filteredEmployees[index++] = list[i];
}
}
// It'll remove the null values:
return Arrays.copyOfRange(filteredEmployees, 0, index);
}
Java 8 Version:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Collectors;
public static Employee[] searchWithId(Employee[] list, String search) {
System.out.println("Searching for the id number: " + search);
return Arrays.asList(list)
.stream()
.filter(e -> e.idNumber.equalsIgnoreCase(search))
.collect(Collectors.toList())
.toArray(new Employee[list.length]);
}
change your searchWithId method to mine:
first way is using ArrayList of Employees
public static Employee[] searchWithId(Employee[] list, String search) {
System.out.println("Searching for the id number: " + search);
ArrayList<Employee> search_result = new ArrayList<>();
for (Employee employee : list) {
if (employee.getIdNumber().equals(search)) {
search_result.add(employee);
}
}
return search_result.toArray(new Employee[search_result.size()]);
}
or you can use array of employee to do this
public static Employee[] searchWithId(Employee[] list, String search) {
System.out.println("Searching for the id number: " + search);
Employee search_result[] = new Employee[list.length];
int index = 0;
for (Employee employee : list) {
if (employee.getIdNumber().equals(search)) {
search_result[index] = employee;
index++;
}
}
return Arrays.copyOfRange(search_result, 0, index);
}
even you can use
public static Employee[] searchWithId(Employee[] list, String search) {
System.out.println("Searching for the id number: " + search);
Employee first_search_result[] = new Employee[list.length];
int index = 0;
for (Employee employee : list) {
if (employee.getIdNumber().equals(search)) {
first_search_result[index] = employee;
index++;
}
}
Employee final_search_result[] = new Employee[index];
for (int i=0; i<first_search_result.length;i++) {
if (first_search_result[i].getIdNumber().equals(search)) {
final_search_result[i] = first_search_result[i];
}
}
return final_search_result;
}
and return final_search_result, to avoid using Arrays.copyOfRange
the above method in any way will return list of all employees with search id
I have an array of messages which are called upon to display in a textfield. I would like to assign the array index i.e. [0] to a variable so that when the person enters the correct text I can get the current array index and increment it to the next one to be able to print out. How can I do this?
I have these methods:
#Override
public void actionPerformed(ActionEvent e) {
String text = commandInput.getText();
messageDisplay.append("\n \n" + text + "\n \n");
commandInput.selectAll();
}
public String getCurrentLevel() {
return currentLevel;
}
After commandInput.selectAll(); I would like to do getCurrentLevel() + 1 to get the next element in the array to append.
Here is the array class it is pulling from:
package com.game.main;
public class Message {
public String[] messageArray;
public Message() {
messageArray = new String[50];
messageArray[0] = "Welcome. ";
}
}
I am not quite sure if this is what you are looking for, but subsequent calls to getNextMessage() will return the next message in the array. Call it too many times and it will go out of bounds etc. This of course assumes you are not recreating the class between calls, if so, you need to make the indx static.
An alternative way to do this using an ArrayList instead of an array:
//using an ArrayList<String>
public class Message {
private int indx = 0;
private ArrayList<String> messages;
public Message() {
messages = new ArrayList<String>();
messages.add("Welcome. ");
}
public String getNextMessage(){
String s = messages.get(indx);
indx++;
return s;
}
// using an array
public class Message {
private int indx = 0;
private String[] messageArray;
public Message() {
messageArray = new String[50];
messageArray[0] = "Welcome. ";
}
public String getNextMessage(){
String s = messageArray[indx];
indx++;
return s;
}