Codes316
Codes316

Reputation: 303

Java: Printing only the First and Last when the names that the user gave are organized alphabetically

I am a bit lost on where I went wrong here is my main file:

import java.util.Scanner;
import java.util.Arrays;
import java.util.*; 
import java.util.TreeSet; 

public class personSorter 
{
  public static void main(String[] args)
  {
  int count = 0; 
  Scanner in = new Scanner(System.in);

  boolean more = true;
  Person first = null;
  Person last = null; 

  Person[] people= new Person[10]; //my array 

  while(more)
  {
  System.out.println("Please enter the person's name or a blank line to quit");
  String names = in.nextLine(); 

  if (names.equals(""))
     {    
     more = false;
     }
 else
 {
        Person p1 = new Person(names);  //creating 10 person objects to be used
        Person p2 = new Person(names);
        Person p3 = new Person(names);
        Person p4 = new Person(names);
        Person p5 = new Person(names);
        Person p6 = new Person(names);
        Person p7 = new Person(names);
        Person p8 = new Person(names);
        Person p9 = new Person(names);
        Person p10 = new Person(names); 

       people[count] = p1; // using my person objects and declaring the index of variable count
       people[count] = p2;
       people[count] = p3;
       people[count] = p4;
       people[count] = p5;
       people[count] = p6;
       people[count] = p7;
       people[count] = p8;
       people[count] = p9;
       people[count] = p10;

        first = people[count];
        last  = people[count];

    TreeSet<String> treeSet = new TreeSet<String>(); //using TreeSort to get the names entered by user in ascending order

     treeSet.add(names);
     treeSet.add(names);
     treeSet.add(names);
     treeSet.add(names);
     treeSet.add(names);
     treeSet.add(names);
     treeSet.add(names);
     treeSet.add(names);
     treeSet.add(names);
     treeSet.add(names);



   first.compareTo(p1); //after TreeSort first compare method called of first object as it is now the first name in alphabet order
   last.compareTo(p10); //after TreeSort last compare method called of last object as it is now the last name in alphabet order

  count++;       
  }
}

//printing out the first and last name(in alphabet order) of the entered names 
  System.out.println("First: " + first.toString()); 
  System.out.println("Last: " + last.toString());
 } 
 }

I used a TreeSet to arrange the names in alphabet order. Then I used the call to compareTo method on object 1 and 10 only because when they are arranged in alphabet order the first object becomes the first name and the last object becomes the last name.

Here is the Person.java:

public class Person implements Comparable <Person> 
    {
        private String name;

public Person(String n) 
{
    name = n;
}

public String getName() 
{
    return name;
}

   @Override
public int compareTo(Person others) 
{
    if (name.compareTo(others.name) == 1) 
    {
        return 0;
    } 
    else if (name.compareTo(others.name) < 0) 
    {
        return -1;
    } 
    else 
    {
        return 1;
    }
   }
   public String toString() 
   {
   return "[" + name + "]";
   }

}

However, the final output is all the names entered by the user in the order they inputted it. As in, the names weren't even in alphabet order. Any help would be much appreciated it!

Upvotes: 0

Views: 1487

Answers (2)

A_Di-Matteo
A_Di-Matteo

Reputation: 27812

Here is a simplified and correctly working version of your code (if I well understood the goal of that main method):

public static void main(String[] args) {
    int count = 0;
    Scanner in = new Scanner(System.in);

    boolean more = true;
    int MAX_SIZE = 10;

    Person[] people = new Person[MAX_SIZE]; // my array

    while (more && count < MAX_SIZE) {
        System.out.println("Please enter the person's name or a blank line to quit");
        String name = in.nextLine();

        if (name.equals("")) {
            more = false;
        } else {
            Person p = new Person(name); 
            people[count++] = p;
        }
    }
    in.close();

    Arrays.sort(people, 0, count);

    // printing out the first and last name(in alphabet order) of the entered names
    System.out.println("First: " + people[0]);
    System.out.println("Last: " + people[count - 1]);
}

Few considerations:

  • You don't need a TreeSort to sort an array, simply use the Arrays.sort method. Also note the further parameters it takes as input to limit it to a start and an end, which don't necessarily match the full initial size of the array (since you are populating it from the console input)
  • To populate different elements of the array, you need to move to its next index, hence the count variable needs to be incremented by one at each new iteration
  • You don't need temp variable for the first and last elements once the array is sorted, simply use the first index (0) and the last populated (count - 1)
  • You also need to limit the whole loop to the maximum size of the array in order not to fall out its size and get an exception

Hope you get a better understanding on loops, arrays, sorting and how your code could have been improved.

Update: The code above will read names one by one, after each enter, till an empty enter has been provided or the MAX_SIZE limit has been reached. If you want to type all names in one shot, you don't even need a loop, your code will be further simplified, but you should then separate the tokens (your names) somehow, otherwise they will all be taken as one big name. Look at the code below, which separates the tokens (the names) using the String.split() method and using " " (space) as tokens separator.

public static void main(String[] args) {
    int count = 0;
    Scanner in = new Scanner(System.in);
    int MAX_SIZE = 10;
    Person[] people = new Person[MAX_SIZE];

    System.out.println("Please enter the person's name or a blank line to quit");
    String line = in.nextLine();

    String[] names = line.split(" ");
    for (int i = 0; i < MAX_SIZE; i++) {
        Person p = new Person(names[i]);
        people[count++] = p;
    }
    in.close();

    Arrays.sort(people, 0, count);

    // printing out the first and last name(in alphabet order) of the entered names
    System.out.println("First: " + people[0]);
    System.out.println("Last: " + people[count - 1]);
}

Upvotes: 1

untilted
untilted

Reputation: 54

you can do the same with the first() and last() methods in TreeSet.Read java documentation for details. http://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html

TreeSet stores values in sorted order and first and last methods return the first and last values in set respectively.

Now coming to your code:

else
{
    Person p1 = new Person(names);  //creating 10 person objects to be used
    Person p2 = new Person(names);
    Person p3 = new Person(names);
    Person p4 = new Person(names);
    Person p5 = new Person(names);
    Person p6 = new Person(names);
    Person p7 = new Person(names);
    Person p8 = new Person(names);
    Person p9 = new Person(names);
    Person p10 = new Person(names);   

You are creating 10 objects with the same value initialized i.e when the it loops for the second pass all objects will contain that second value and the initial value will be lost .In that case your objects will contain only last entered values.

    people[count] = p1; // using my person objects and declaring the index of variable count
    people[count] = p2;
    people[count] = p3;
    people[count] = p4;
    people[count] = p5;
    people[count] = p6;
    people[count] = p7;
    people[count] = p8;
    people[count] = p9;
    people[count] = p10;

    first = people[count];
    last  = people[count];

And then you are assigning those same objects to the same array element(same index) ten times. After this you are assigning this object to first and last variable.So after all this iteration first and last will contain the last element user entered. And compareTo method returns integer which is captured nowhere and comparing is of no use when you are using treeset(in this case).

first.compareTo(p1); //after TreeSort first compare method called of first object as it is now the first name in alphabet order
last.compareTo(p10); //after TreeSort last compare method called of last object as it is now the last name in alphabet order

All in all either you are trying to do something else or you have used a wrong logic. Insert names in a treeset and use first and last methods to get the name.

Upvotes: 0

Related Questions