Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

The objective of this exercise is to write a program that reads a number of Stri

ID: 643459 • Letter: T

Question

The objective of this exercise is to write a program that reads a number of Strings and sorts them by inserting each string into the appropriate place in an arraylist. For example, if the strings are: Shai Ralph Hillary Tom Barbara Fred Then the arraylist should grow as follows: [Empty] [Shai] [Ralph, Shai] [Hillary, Ralph, Shai] [Hillary, Ralph, Shai, Tom] [Barbara, Hillary, Ralph. Shai, Tom] [Barbara, Fred, Hillary, Ralph. Shai, Tom] The algorithm to sort is simple. As you read each name (say name 1), compare it with each name (say name2) stored in the arraylist starting from the index 0. As soon (name1.compareTo(name2) > 0), that is the right index to put name 1. Be sure that you do not cross the arraylist boundary.

Explanation / Answer

import java.util.ArrayList;

import java.util.Scanner;

public class ArrayListSort

{

            public static void main(String[] args)

            {

                        Scanner keyboard = new Scanner(System.in);

                        ArrayList<String> namesList = new ArrayList<String>();

                        System.out.println("Enter names, end with -1:");

                        String newWord = keyboard.nextLine();

                        while (!newWord.equals("-1"))

                        {

                       

                                                boolean found = false;

                                                int i;

                                                for(i=0; i<namesList.size()&&!found; i++)

                                                {

                                                            if (newWord.compareTo(namesList.get(i))<0)

                                                                        found = true;

                                                }

                                                if (found)

                                                            namesList.add(i-1, newWord);

                                                else

                                                            namesList.add(newWord);

                                                System.out.println(namesList);

                                                newWord = keyboard.nextLine();

                       

                        }

            }

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote