How do you arrange an array with multiple objects alphabetically? [closed] - java

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 2 years ago.
Improve this question
I have an assignment that goes like this:
Create a program that functions as an address book. It should have entries containing the following information: first and last name, phone number and email address. The entries should be sorted by last name. Every new contact will be inserted in such a way as to maintain the alphabetical order. Upon each change a display of all the entries is required.
Ive read several articles in this site but none of them worked, I tried the sort method but it didnt work.
edit: Hi! I tried your suggestions and its now printing like this, I also updated the code.
[com.mycompany.test.contact#b4c966a, com.mycompany.test.contact#2f4d3709, com.mycompany.test.contact#4e50df2e]
public class NewClass {
String firstname;
int phone;
String email;
int i=0;
public static void main(String[]args){
String lastname;
String firstname;
int phone;
String email;
Scanner scanner = new Scanner(System.in);
contact[] contacts = new contact[3];
for(int i=0; i<contacts.length; i++){
System.out.println("Please enter Last name:");
lastname = scanner.next();
System.out.println("Please enter sFirst name:");
firstname = scanner.next();
System.out.println("Please enter Phone number:");
phone = scanner.nextInt();
System.out.println("Please enter Email address:");
email = scanner.next();
contacts[i] = new contact(lastname,firstname, phone, email);
}
Arrays.sort(contacts);
for (int i=0; i<contacts.length; i++) {
System.out.println(Arrays.toString(contacts));
}
}
}
public class contact implements Comparable {
private String lastname;
private String firstname;
private int phone;
private String email;
public contact(String lastname, String firstname, int phone, String email){
this.lastname=lastname;
this.firstname=firstname;
this.phone=phone;
this.email=email;
}
public String getlastname(){
return lastname;
}
public String getfirstname(){
return firstname;
}
public int phone(){
return phone;
}
public String getlastemail(){
return email;
}
#Override
public int compareTo(contact contact){
return lastname.compareTo(contact.lastname);
}
public String tostring(){
return "Lastname: "+ this.lastname + "Firstname: " + this.firstname + "Phonenumber :" + this.phone + "Email: " + this.email;
}
}

You need to either implement Comparable or Comparator interfaces and override their respective methods.
Also, use TreeSet to maintain the address book. All newly added contacts will be automatically sorted. I have created a quick example:-
import java.lang.Comparable;
import java.util.*;
public class ContactTester{
public static void main(String args[]){
Contact c1 = new Contact("PA" , "GC", "000-987-9876","a#b.com");
Contact c2 = new Contact("VA" , "AA", "000-987-9876","a#b.com");
Contact c3 = new Contact("SA" , "AA", "000-987-9876","a#b.com");
Contact c4 = new Contact("AC" , "AB", "000-987-9876","a#b.com");
TreeSet<Contact> addressBook = new TreeSet();
addressBook.add(c1);
addressBook.add(c2);
addressBook.add(c3);
addressBook.add(c4);
for (Contact c : addressBook)
System.out.println(c.toString());
Contact c5 = new Contact("TT" , "AT", "000-987-9876","a#b.com");
addressBook.add(c5);
for (Contact c : addressBook)
System.out.println("after " + c.toString());
}
}
class Contact implements Comparable<Contact>{
private String firstname;
private String lastname;
private String phoneNumber;
private String email;
public Contact(String firstname, String lastname, String phoneNumber, String email){
this.firstname = firstname;
this.lastname = lastname;
this.phoneNumber = phoneNumber;
this.email = email;
}
#Override
public int compareTo(Contact contact){
int last = this.lastname.compareTo(contact.lastname);
return last ==0 ? this.firstname.compareTo(contact.firstname) : last;
}
#Override
public String toString(){
return "firstname "+ this.firstname + " lastname " + this.lastname + " phoneNumber " + this.phoneNumber + " email " + this.email;
}
}

It's been a while since I did Java programming, but there's a lot of formatting and some syntax advice I could give, but that's not on topic at the moment. I've edited the Q to make some things a little better to read, including putting the code in a code block, if that gets approved.
So first things first:
Your array sort is in the loop, which it shouldn't be. You should only do that after you've done all your input. At least in this case. There may be times when it's appropriate to put a sort in a loop, but not this time.
Secondly:
You also need to move the println outside the loop as well, which means you'll need to create a new loop to display all the contacts. You can reuse the i variable, since it'll be out of scope of the first loop, so there's no problems with mangling other uses of that variable.
You can also take a look at the below Question if you have any questions about that.
List an Array of Strings in alphabetical order
Third:
I said I wasn't going to talk about formatting, but I'll take a brief dive into it. Your contact variable should be a different name than your contact class. Even if that means capitalizing the class name, that should be good enough for most cases, at least while you're still learning. It's not usually good for a seasoned professional, but sometimes it happens anyway. But it should be rare.
Also, you could create a new instance of a blank contact, then simply assign the values directly to that object, instead of having the extra variables. Those variables could retain data that gets leaked to other contact. The below Question shows how to add an element to an existing array. It's about ints, but it works the same for all arrays.
Adding integers to an int array
And this Question is about how to assign to a variable from an object property. It's the opposite of what you're doing, but you just need to reverse the assignment. Their example is double height1 = oldRectangle.height;, so reversing it would be oldRectangle.height = height1;.
How to assign an object property value to a variable in Java?
Since you don't include the contact class definition, I don't know the specifics, but I'll guess that you can do something like this:
Contact newContact = new Contact(); // at the beginning of the loop
...
newContact.LastName = scanner.next();
...
newContact.FirstName = scanner.next();
...
newContact.Phone = scanner.next();
...
newContact.Email= scanner.next();
...
contact.Add(newContact); // at the end of the loop
This also assumes that a new contact doesn't require those parameters and you can just create a blank contact. If it does require those params, you can still do it but instead do new Contact("", "", "", "");. It might annoy your instructor, or it might be a requirement of the assignment to use variables and the current instantiation, with my suggestions being ahead of your current learning point.
Hmm, that wasn't so brief. Sorry. I'm sure your prof/teacher/instructor will teach you more about proper formatting and other Best Practices later, so I really won't go further than I already have.

Related

Adding to an ArrayList using a TUI

I'm implementing a class called "BorrowerTUI" to an existing project for an assignment. I've been trying for hours and I just can't work out how to add to my ArrayList using the TUI. The information that needs to be added is in a class called "Borrower". Here is the constructor:
public Borrower(String fName, String lName, String lNumber, int numberOfBooks,
String street, String town, String postcode)
{
firstName = fName;
lastName = lName;
libraryNumber = lNumber;
noOfBooks = numberOfBooks;
address = new Address(street, town, postcode);
}
Previously, I added the object to the ArrayList using a different class called "BorrowerList". Here is the method:
public void addBorrower(Borrower borrower)
{
borrowers.add(borrower);
}
That works with no problems. Now what I'm trying to do is use a TUI to add the same information to the same ArrayList. Here is the constructor for "BorrowerTUI" and the options the user will have:
private BorrowerList borrowerList;
private Scanner myScanner;
public BorrowerTUI()
{
myScanner = new Scanner (System.in);
borrowerList = new BorrowerList();
Borrower borrower;
}
private void displayMenu()
{
System.out.println("To add a borrower........................[1]");
System.out.println("To get the total number of borrowers.....[2]");
System.out.println("To remove a borrower.....................[3]");
System.out.println("To show all borrowers....................[4]");
System.out.println("To show a single borrower................[5]");
System.out.println("To close Borrowers.......................[0]");
}
private void addBorrower()
{
borrowerList.addBorrower();
}
That doesn't work and I have tried to implement other solutions with no joy. I tried something along the lines of:
private void addBorrower()
{
myScanner = new Scanner(System.in);
String firstName;
String lastName;
borrower = (firstName, lastName);
System.out.println("Enter your first name: ");
myScanner.nextLine() = firstName;
System.out.println("Enter your last name: ");
myScanner.nextLine() = lastName;
borrowerList.add(borrower);
}
That was a bit of guess work as we haven't actually covered this material in class, we're expected to work it out ourselves having briefly touched on TUIs. Hopefully this is enough information, please let me know if you need me to elaborate or provide any additional code.

Generate non repeating numbers to add to customerNumber int variable

I'm creating a banking app and I need to generate a customer number starting from number 1, keeping track of the number so that it won't repeat itself each time I enter the loop and store it into an int variable that I can use to collect the value and pass it to the customerNumber variable outside the loop. I've tried a few things like arraylists and arrays, but I was getting troubles in passing the values to the variable I wanted. Thanks in advance and sorry for my terrible noobishness...I'm new in programming... Here's what I've got so far:
import java.util.ArrayList;
public class Bank{
public void addCustomer(String name, int telephone, String email, String profession) {
ArrayList customerList = new ArrayList();
Customer customer = new Customer();
customerList.add(customer);
}
}
public class Customer{
private String name;
private int telephone;
private String email;
private String profession;
private int customerNumber;
public Customer() {
}
}
public class Menu {
Scanner sc = new Scanner(System.in);
Bank bank = new Bank();
private void createCustomer() {
String name, email, profession;
int telephone, customerNumber;
System.out.println("Enter the customer's number: ");
name = sc.nextLine();
System.out.println("Enter the customer's telephone: ");
telephone = sc.nextInt();
System.out.println("Enter the customer's email: ");
email = sc.nextLine();
System.out.println("Enter the customer's profession: ");
profession = sc.nextLine();
bank.addCustomer(name, telephone, email, profession);
}
}
One thing you can do is create a singleton class, and request a number each time you need one. The singleton class keeps a list of the numbers that have been used already, and thus can return a number that has not been used before.
If you need also to generate new numbers after your application is restarted, then you can store all numbers in a file, and read that file whenever needed.
A singleton class, is a class that can have max 1 instance. You can achieve this by making the constructor private, and creating a public static method (usually called something like getInstance() ) to get an instance of this class. This getInstance() returns the ref to the only instance, and if no instance was created yet, it first creates one.
Then, this only instance knows all account numbers in use (inyour case), regardless how often an instance of this class is requested.
The responsibility of this class is to maintain the account nrs: create a nr, print them, save them, read them, ...
Example:
private AccoutnNr singleInstance;
private AccountNr(){
}
public AccountNr getInstance(){
if (singleInstance == null) {
singleInstance = new AccountNr();
}
return singleInstance;
}
public int getAccountNr{
// do whatever is needed to create an account nr
}
more methods if you need to do more than creating account numbers

how do i add or delete something from an array?

I am writing this program that will take in the names, ages and salaries for 5 different people from the user and will put them in an array.
I then want to write a method that will ask the user for another name, age and salary and add that into the array. Also a method that will as for the name of someone who's already in the array and will delete the information of the person with that age from the array.
The first method will increase the array size by 1 and the second will decrease the array size by 1. so far this is what I have:
ArrayList<details> details = new ArrayList<details>();
for(int x = 0; x < 4; x++) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the first name: ");
String firstName = scan.nextLine();
System.out.println("Enter the last name: ");
String lastName = scan.nextLine();
System.out.println("Enter the age: ");
int age = scan.nextInt();
System.out.println("Enter the salary: ");
double salary = scan.nextDouble();
details.add (new details(firstName, lastName, age, salary));
}
I don't know how to go about doing this. I need some help!
thanks!
You can have a class Person with the class variables you require (name,age,salary)
class Person {
private int age;
private dobule salary;
private String firstname;
private String lastname;
}
Define the getter and setter methods for each of the class variables. For e.g
public void setAge(int age){
this.age = age;
}
public int getAge(){
return this.age;
}
In your main class read the input from STDIN as you are doing it. Instantiate the Person object for each of the 5 person.
Person employee = new Person();
employee.setAge(x);
employee.setFirstName(x);
employee.setLastName(y);
employee.setSalary(y);
Now, you can add each Person to your list and remove them too.
For removing any Person you would have to search for the Person through the ArrayList by name. That would be iterating over the length of ArrayList and comparing the name of each.
The final class would look like,
public class Solution{
private ArrayList<Person> details = new ArrayList()<Person>;
public static void main(){
// Here you loop for reading from STDIN as you are already doing.
// addPerson() would be used to add to ArrayList and removePerson() for the other
}
public addPerson(String firstName, String lastName, int age, int salary){
//Create the Person object
details.add(<person object>);
}
public removePerson(name){
details.remove(index);
// to get index it would require iterating over the ArrayList.
// It would be better if you use a Map instead (as other suggest)
// with name as the key
}
}
Hope this helps.
dud first of all, i can see that u have used arrayList name & Class name both same so please update that.
secondary use Map in place of Class like in if condition
if(){
Map userDetails = new HashMap();
map.put("firstname",firstname);
..
..
map.put("salary",scan.nextDouble());
details.add(map)
}
and on time of delete iterate ArrayList
for(int i=0;i<details.size();i++){
Map tempMap = details.get(i);
if(temp.get("firstname").toString() == "Given Name"){
}else{
// your logic
}
}
Hope will help you please let me know if any doubts.
use this code for removing employee
void removeEmployee(String name){
for(Employee emp :details){
if(name.equals(emp.getName())){
details.remove(emp);
break;
}
}
}
and do include exception handling

How to read a text file into an array with private fields using mutators in Java

I have Googled this for a couple of days without much luck. I am trying to read a text file and use that information to populate the private fields of an array for a class object. I am new to Java and pretty new to programming in general.
What I've come up with for reading into the array seems really clunky and I feel there must be a better way, but I cannot find a good example for this particular kind of case case.
Creating a bunch of string variables was the only way I could get this to work. Perhaps main is a bad place to do this; perhaps Scanner is a poor choice here?
What better ways are there to implement this situation?
My text file that contains Strings and integers separated by whitespace on lines is similar to this:
Joe 2541 555-1212 345 1542 Type
Bob 8543 555-4488 554 1982 Type
... etc.
Here's my majority of my code thus far which is within main:
Scanner in = new Scanner(new FileReader("accounts.txt")); //filename to import
Accounts [] account = new Accounts [10];
int i = 0;
while(in.hasNext())
{
account[i] = new Accounts();
String name = in.next();
String acct_num = in.next();
String ph_num = in.next();
String ss_num = in.next();
int open_bal = in.nextInt();
String type = in.next();
account[i].setName(name);
account[i].setAcctNum(acct_num);
account[i].setPhoneNum(ph_num);
account[i].setSSNum(ss_num);
account[i].setOpenBal(open_bal);
account[i].setType(type);
i++;
}
class Accounts
{
public Accounts()
{
}
public Accounts(String n, String a_num, String ph_num,
String s_num, int open_bal, String a_type, double close_bal)
{
name = n;
account_number = a_num;
phone_number = ph_num;
ssn = s_num;
open_balance = open_bal;
type = a_type;
close_balance = close_bal;
}
public String getName()
{
return name;
}
public void setName(String field)
{
name = field;
}
public String getAcctNum()
{
return account_number;
}
public void setAcctNum(String field)
{
account_number = field;
}
//And so forth for the rest of the mutators and accessors
//Private fields
private String name;
private String account_number;
private String phone_number;
private String ssn;
private int open_balance;
private String type;
private double close_balance;
}
I believe you need to split each line in order to get the data contained in each line. You can use the split() of the string class which will return a string[]. Then you can go through each index of the string array and pass them to the mutator methods of the account class.
Something like this maybe.
while(in.hasNext())
{
// will take each line in the file and split at the spaces.
String line = in.next();
String[] temp = line.split(" ");
account[i].setName(temp[0]);
account[i].setAcctNum(temp[1]);
account[i].setPhoneNum(temp[2] + "-" + temp[3]);
account[i].setSSNum(temp[4]);
account[i].setOpenBal((int)temp[5]);
account[i].setType(temp[6]);
// will account for blank line between accounts.
in.next();
i++;
}
The phone number gets split into two separate indices so you have to rejoin the phone number by accounting for the first 3 digits being in one index and the last 4 being in the next.
Replacing Accounts[] with Set<Accounts> would be more flexible solution as you can process either 10 lines or 10000 accounts without code changes. In general: Consider Collections vs arrays
Using Scanner seems to be reasonable in this particular case, however take a look at the others ways of processing text (performance vs convenience): Scanner vs. StringTokenizer vs. String.Split
Setting up account parameters with mutators or constructor might not be the best choice: Effective Java: Consider a builder when faced with many constructor parameters

How to load an ArrayList with instances of an Object I created

NOTE: I edited my code to how I think people are trying to tell me but it still doesn't give me my desired output. Now my output is "examples.search.Person#55acc1c2" however many times I enter new first and last names. At least it's making it through the code with out crashing lol
I am learning how to use ArrayLists and need to load an Array list with instances of an Object I created. I know how to do this with an array but for this assignment I need to do it with an ArrayList. Here's an example of what I need to do.
// my "main" class
package examples.search;
import java.util.ArrayList;
import dmit104.Util;
public class MyPeople {
public static void main(String[] args) {
ArrayList<Person> people = new ArrayList<Person>();
Person tempPerson = new Person();
String firstName;
String lastName;
char choice = 'y';
int count = 1;
// fill my ArrayList
do {
people.add(tempPerson);
// I have a Util class that has a prompt method in it
firstName = Util.prompt("Enter First Name: ");
lastName = Util.prompt("Enter Last Name: ");
tempPerson.setFirstName(firstName);
tempPerson.setLastName(lastName);
count++;
choice = Util.prompt(
"Enter another person? [y or n]: ")
.toLowerCase().charAt(0);
} while (choice == 'y');
// display my list of people
for(int i = 0; i < people.size(); i += 1) {
System.out.print(people.get(i));
}
}
}
// my Person class which I am trying to build from
public class Person {
// instance variables
private String firstName;
private String lastName;
// default constructor
public Person() {
}
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;
}
}
I've tried it a number of ways but no matter what my ArrayList doesn't fill up. Like I mentioned I can do it no problem with an array or even if I had a loaded constructor method but I don't. In my actual assignment I am supposed to do it with the set methods.
I have looked everywhere and cannot find the solution for my problem and being friday my instructor isn't in.
Thank you so much in advance
Leo
You'll have to create a Person and then add it to the ArrayList.
for (int i = 0; i < count; i++) {
Person person = new Person();
person.setFirstName("Foo");
person.setLastName("Bar");
people.add(person);
}
Its crashing because your line people.get(i).setFirstName(firstName); is first trying to what is at index i, but you have not set anything yet.
Either first set people[i] to a empty Person, or make a person using firstName and lastName, and add it to people using people.add(person);
You have an ArrayList<Person>, but that alone only defines a list of potential Person instances. But so far, each of the list entries is null. The get(i) returns null, and the following null.setFirstName(..) causes a NullPointerException.
So you need to create the instances of Person that are supposed to go into the list:
firstName = Util.prompt("Enter First Name: ");
Person p = new Person(); //create the instance
people.add(p); //add the instance to the list
p.setFirstName("..."); //set any values
Now you are storing the Person Object into an ArrayList and printing that Object.
To print the firstname and lastName when you print the Person object, you will have to override toString method.
Add the following code in your Person class
public String toString(){
return String.format("[Personn: firstName:%s ,lastName: %s]", firstName,lastName);
}
As for the second question you had, you have to override the toString() method in the Person class. The outputs you are getting, such as examples.search.Person#55acc1c2 is the default toString() method from the Object class, which is defined as class#hashCode

Categories