Sorting First and Last Names Array - java

I am making a program and I need to sort this list of first and last names for a seating chart making method on an airplane. It is a 2 dimensional array the first column has the first name, and the second column has the last name of the corresponding person in the first column. I need to sort this in alphabetical order by last name, first name but I cannot figure out how to sort the last name and then keep the corresponding last name.
This is my Code:
package assignment_6_1;
import java.util.Scanner;
import java.util.Arrays;
public class Assignment_6_1 {
public static void main(String[] args) {
//Create a Scanner
Scanner input = new Scanner(System.in);
//Create int & string []
String[][]firstAndLastNames = new String[36][2];
int[]heightOfPerson = new int[36];
String[][]seatingChartDiagram = new String[9][4];
int[][]seatRequest = new int [36][2];
//Gather list of names and heights
for(int i=0; i<heightOfPerson.length; i++)
{
//Get first name
System.out.println("Enter Your First Name: ");
firstAndLastNames[i][0] = input.next();
//Get last name
System.out.println("Enter Your Last Name: ");
firstAndLastNames[i][1] = input.next();
//Get height in inches
System.out.println("Enter your height (Iches) : ");
heightOfPerson[i] = input.nextInt();
//Is there a seat request or not
System.out.println("Do you want to request a seat ?");
String ifSeatRequest = input.next();
//Get seat request
if(ifSeatRequest.equals("Yes") || ifSeatRequest.equals("yes"))
{
System.out.println("Enter the seat row you want: ");
seatRequest[i][0] = input.nextInt();
System.out.println("Enter the seat number you want in that row: ");
seatRequest[i][1] = input.nextInt();
}
else
{
//set the request colum for that person to 0 for no request
seatRequest[i][0] = 0;
seatRequest[i][1] = 0;
}
//Prints passenger manifest when list is full
if(firstAndLastNames[35][1] != null){
System.out.println("All Seats are Filled");
break;}
}
String[]firstNameSort = new String[36];
//put the first names into another array to sort
for(int j=0; j<heightOfPerson.length; j++)
{
firstNameSort[j] = firstAndLastNames[j][1];
}
//Alphabetize first name list
Arrays.sort(firstNameSort);
String[][]firstNameAlphLast = new String[36][2];
String[][]nameAlph = new String[36][2];
}
}
In order: It takes in user input for 36 names, heights, and if the person wants to make a seating request. I made it copy the array 2 another array, and then I alphabetized the last names. Now i can't figure out how to get the corresponding first names for the alphabetized last names.

Try this sort:-
Arrays.sort(firstAndLastNames, new Comparator<String[]>() {
#Override
public int compare(final String[] a1, final String[] a2) {
return a1[1].compareTo(a2[1]) + a1[0].compareTo(a2[0]);
}
});

You should use a sorting algorithm. You can discover them here : Sorting algorithms. You have some sample code for each method.
Be careful when comparing strings, you should use the method compareTo() method as follows :
string1.compareTo(string2);
Results:
-1 if string1 is before string2 in the alphabetical order : "Hello".compareTo("World");
0 if string1 is exactly the same than string2 : "Hello".compareTo("Hello);
1 if string1 is after string2 in the alphabetical order : "World.compareTo("Hello");
If you choose to create another array to store your sorted array, juste create one with the same parameter. Here, create this one :
String[][] firstAndLastNamesSorted = new String[36][2];
For your example, you should also sort both firstAndLastNames and seatRequest arrays at the same time according to your sorting criteria.

Related

Taking user input and adding it an array

My program uses an array: collection[] to hold information on cars. user input is used to add a car to the array using the console. So the user would enter the car's name, year of make, etc. However when it gets added to the array it goes straight into collection[0]. So if there is anything already in collection[0] it will replace it.
I want the user input to be but into the the next null cell in the array to avoid this problem. I have tried to write code that goes through each cell of the array and once it finds a cell which is null it then adds the information into it. However it is not working.
public void addCarInput1()
{
for (int i = 0; i < 1; i++)
if (this.collection[i] = null)
{
this.collection[i].addCarInput();
}
}
Here is a shortened version of addCarInput:
Scanner sin = new Scanner(System.in);
System.out.print("Enter car make: ");
Cmake = sin.nextLine();
System.out.print("Enter car model : ");
Mname = sin.nextLine();
You can try something like this if you want more cars
String shouldContinue = null;
while(true) {
if (shouldContinue.equals("no")) break;
Scanner sc = new Scanner(System.in);
System.out.print("Enter car make: ");
String make = sc.nextLine();
System.out.print("Enter car model : ");
String model = sc.nextLine();
//add car info
addCarInput(make, model);
System.out.print("Enter info for another car? : ");
shouldContinue = sc.nextLine()
}
Why don't you use a LinkedList or an ArrayList object instead of an array?
the add() method will add the elements at the end of the list & not replace the old values
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
https://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html
http://examples.javacodegeeks.com/core-java/util/arraylist/arraylist-in-java-example-how-to-use-arraylist/

Sorting names entered by the user in alphabetical order according to the last name

I have completed most of the code by myself (with the help of a bit of Googling) but I have run into an unexpected problem. First-off, I have to sort a user entered list of names in aplhabetical order of their last names using selection sort. Here is my code:
import java.util.*;
class Name_Sort
{
public static void main (String args[])
{
Scanner in = new Scanner (System.in);
System.out.print ("Enter the number of names you wish to enter: ");
int n = in.nextInt();
String ar[] = new String [n];
for (int i = 0; i<ar.length; i++)
{
System.out.print("Please enter the name: ");
ar[i]= in.nextLine();
}
String temp;
for (int b = 0; b<n; b++)
{
for (int j=b+1; j<n; j++)
{
if ((compareLastNames(ar[b], ar[j]))>0)
{
temp = ar[b];
ar[b] = ar[j];
ar[j] = temp;
}
}
}
System.out.println ("The names sorted in alphabetical order are: ");
for (int a = 0; a<n; a++)
System.out.print (ar[a]+"\t");
}
private static int compareLastNames(String a, String b)
{
int index_a = a.lastIndexOf(" ");
String surname_a = a.substring(index_a);
int index_b = b.lastIndexOf(" ");
String surname_b = b.substring(index_b);
int lastNameCmp = surname_a.compareToIgnoreCase(surname_b);
return lastNameCmp;
}
}
The problem (I think) is arising when I'm taking the names from the user, specifically, this part:
Scanner in = new Scanner (System.in);
System.out.print ("Enter the number of names you wish to enter: ");
int n = in.nextInt();
String ar[] = new String [n]; //Array to store the names in.
for (int i = 0; i<ar.length; i++)
{
System.out.println("Please enter the name: ");
ar[i]= in.nextLine();
}
The output on the terminal window of BlueJ shows up as
Name_Sort.main({ });
Enter the number of names you wish to enter: 5
Please enter the name:
Please enter the name:
That is not what it's supposed to display. What could I be doing wrong? I've pondered over it for a while, but nothing comes to mind.
And, even if I do move forward and enter a few names despite the error above, I get another error in this part of my code here:
private static int compareLastNames(String a, String b)
{
int index_a = a.lastIndexOf(" ");
String surname_a = a.substring(index_a);// This is the line the compiler highlights.
int index_b = b.lastIndexOf(" ");
String surname_b = b.substring(index_b);
int lastNameCmp = surname_a.compareToIgnoreCase(surname_b);
return lastNameCmp;
}
the error is :
java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (injava.lang.String)
Does this mean that the white-space character " " is not present? But why?
This is a screenshot of the terminal window:
http://imgur.com/l7yf7Xn
The thing is, if I just initialize the array with the names first (and not take any input from the user) the codes runs fine and produces the desired result. Any help please?
Also, since I know some people here are very particular about this, yes, this is a homework assignment, yes, I did do all of the code by myself, I googled on how to sort the names in alphabetical order as I couldn't exactly code out the original idea I had.
Which was comparing the ASCII values of each character of two surnames to see which should come first. Like: if((int) surname1.charAt(0)>(int) surname2.charAt(0)) then surname2 should come before surname1, else if they both have the same first character, take the second character and so on.
Thanks for taking the time to read this.
The problem is with the in.nextInt() command it only reads the int value. So when you continue reading with in.nextLine() you receive the "\n" Enter key. So to get around this you will have to add an extra in.nextLine() before going into the loop. Or, use another scanner.
int n = in.nextInt();
String ar[] = new String [n]; //Array to store the names in.
in.nextLine(); // < --- an extra next Line
for (int i = 0; i<ar.length; i++)
{
System.out.println("Please enter the name: ");
ar[i]= in.nextLine();
}

Reading values to array, inside a loop

I am trying to build a program which allows a user to input an actors name and details (age+address) and also 2 films they've starred in. These films must be read into a main array in the main method, but each individual actors films must be copied into a designated array in my actor class to store the actors films individually.
I am currently trying to read the values into my array inside a loop in my main method:
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner kbd = new Scanner (System.in);
String code="";
System.out.println("How many actors would you like to enter?");
int amt = kbd.nextInt();
int noOfFilms = (amt*2);
Actor [] arrayOfActors = new Actor[amt];
//Array of ALL films, each actors films must be copied to seperate array in the actor class.
String [] allFilms = new String[noOfFilms];
kbd.nextLine();
int count = 1;
int i = 0;
do {
count++;
System.out.println("Enter the Details for actor "+(count-1)+"\n");
System.out.println("Enter actor name:"+"\n");
String name = kbd.nextLine();
System.out.println("Enter actor age:"+"\n");
int age = kbd.nextInt();
kbd.nextLine();
System.out.println("Enter actor address:"+"\n");
String address = kbd.nextLine();
//Read in the actors films
System.out.println("Enter film 1 for "+name+"\n");
String film1 = kbd.nextLine();
allFilms[i] = film1;
System.out.println("Enter film 2 for "+name+"\n");
String film2 = kbd.nextLine();
allFilms[i+1] = film2;
//Create an actor as array is full of references only.
arrayOfActors[i] = new Actor(name, address, age);
i++;
arrayOfActors[i-1].print();
} while (count <= amt);
System.out.println("This was in the films array: "+allFilms[1]);
}
}
Obviously the way I have it structured currently will not work as every time the loop starts the values will just be over-written and the only details stored will be the last actors films to be entered.
I am stuck trying to work around this and read in all the films, which will then need to be deep copied into another array. (in Actor class)
This is a college assignment and must be done this way. Any suggestions would be of great help.
You can include an array field inside your Actor class. Then you will modify your Actor class constructor in order to include this array argument for initialization purposes.
So I would handle this part inside the loop like this:
String[] actorFilms = new String[2];
//Read in the actors films
System.out.println("Enter film 1 for "+name+"\n");
String film1 = kbd.nextLine();
allFilms[i] = film1; //not OK; read below
actorFilms[0] = film1;
System.out.println("Enter film 2 for "+name+"\n");
String film2 = kbd.nextLine();
allFilms[i+1] = film2; //not OK; read below
actorFilms[1] = film2;
//Create an actor as array is full of references only.
arrayOfActors[i] = new Actor(name, address, age, actorFilms);
I'm not sure if you still need to keep the allFilms array, but if you need, you will have to determine the indexes you need to populate depending on the count value. By simply using i and i+1 you always overwrite the same locations in the array.
Some other remarks:
-- I think you're not using count properly; you're initializing it with 0, but you immediately increment it (first statement in the loop);
-- notation conventions in Java state that class names should be capitalized.
I would suggest use a collection of actor objects in a collection.
Collection actorDetails= new ArrayList<>();
do
{
....
...
....
actorDetails.add(actioObj)
}while(....)
finally use actorDetails to retriev information
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner kbd = new Scanner (System.in);
String code = "";
System.out.println("How many actors would you like to enter?");
int amt = kbd.nextInt();
int noOfFilms = (amt * 2);
Actor[] arrayOfActors = new Actor[amt];
String[] allFilms = new String[noOfFilms];
kbd.nextLine();
for (int count = 0; count < amt; count++) {
System.out.println("Enter the details for actor " + (count + 1));
System.out.prinln("Enter actor name:");
String name = kbd.nextLine();
System.out.println("Enter actor age:");
int age = kbd.nextInt();
kbd.nextLine();
System.out.println("Enter actor address:");
String address = kbd.nextLine();
System.out.println("Enter film 1 for " + name);
String film1 = kbd.nextLine();
allFilms[count * 2] = film1;
System.out.println("Enter film 2 for " + name );
String film2 = kbd.nextLine();
allFilms[(count * 2) + 1] = film2;
arrayOfActors[count] = new Actor(name, address, age);
arrayOfActors[count].print();
}
System.out.println("This was in the films array: " + allFilms[1]);
}
}
Perhaps something like this? I got rid of the i variable and used only the count variable to keep track of the array indexes. I am assuming you have not began working with Collections, otherwise you could do that.

Input and storing Strings in two-dimensional arrays

My teacher explained two dimensional arrays in literally two paragraphs. He didn't give me any information on how to create them besides that and now I have to do an assignment.
I've read up a lot about it and I somewhat understand how a 2D array is like an array of arrays, but I'm still completely and utterly confused about how to apply it.
The assignment itself is very simple. It asks me to create a program that will ask a user for ten Criminal Records, (name, crime, year). This program will store the records in a two-dimensional array and then sort them using the selection sort.
I know this is probably wrong, but here is what I have so far based on what I've read:
public static void main(String[] args)throws IOException {
//create array
String[][] Criminals = new String[10][3]; // create 3 columns, 10 rows
int i, j;
int smallest; //smallest is the current smallest element
int temp; //make an element swap
String line;
//loop to request to fill array
for (int row = 1; row < Criminals.length; row++){
for (int col = 1; col < Criminals[row].length; col++){
System.out.print("Enter a criminal name: ");
Criminals[row][col] = br.readLine();
}
}
}
So far, I'm just trying to get the input and store it.
(Please try to be patient and thorough with me! Coding isn't my strongest point, but I'm trying to learn.) Any help would be amazing! Thanks in advance. :)
It looks fine for the most part. You should index arrays starting from 0, not 1. Your current code works but I'm guessing you don't want the same prompt for all entries. Thus it may be a good idea to use a single loop instead:
for (int row = 0; row < Criminals.length; row++) {
System.out.print("Enter a criminal name: ");
Criminals[row][0] = br.readLine();
System.out.print("Enter a crime: ");
Criminals[row][1] = br.readLine();
System.out.print("Enter a year: ");
Criminals[row][2] = br.readLine();
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
//create array
String[][] criminals = new String[10][3]; // create 3 columns, 10 rows
int i, j;
int smallest; //smallest is the current smallest element
int temp; //make an element swap
String line;
//loop to request to fill array
for (int row = 0; row < criminals.length; row++){
System.out.print("Enter a criminal name: ");
while(in.hasNext()){
criminals[row][0] = in.nextLine();
System.out.print("Enter a crime: ");
criminals[row][1] = in.nextLine();
System.out.print("Enter a year: ");
criminals[row][2] = in.nextLine();
}
}
}
}
This will print the commands you need from user and will store it in criminals. You may sort in the end. Since you didn't gave any information how you want it sorted, I will leave it for you to do it.
PS: I changed the 2d array name from Criminals to criminals, it's a java's good practice to not use capital words for attributes and variables (use it only for class names)

How do you find the index number of a string in an array in Java

I have no idea if I'm coding this efficiently, or even correctly, but I want to input a name, address, and phone number. I then want to have input find a match from the input array, and use that same index number to print the corresponding information.
import java.util.*;
public class NameAddress {
public static void main(String[] args) {
Scanner ui = new Scanner(System.in);
System.out.println("Welcome to the name collecting database");
String []names = new String[5];
String []address = new String[5];
String []phone = new String [5];
int count =0;
while (count<=5)
{
System.out.println("Please enter the name you would like to input");
names[count] =ui.next();
System.out.println("Name has been registered into Slot "+(count+1)+" :"+Arrays.toString(names));
System.out.println("Please enter the address corresponding with this name");
ui.nextLine();
address[count] = ui.nextLine();
System.out.println(names[count]+" has inputted the address: "+address[count]+"\nPlease input your phone number");
phone[count]=ui.nextLine();
System.out.println(names[count]+"'s phone number is: "+phone[count]+"\nWould you like to add a new user? (Yes or No)");
if (ui.next().equals("No"))
{
System.out.println("Please enter a name to see matched information");
String name = ui.next();
if(name.equals(names[count]))
{
System.out.println("Name: "+names[count]+"\nAddress: "+address[count]+"\nPhone: "+phone[count]);
}
count=6;
}
count++;
}
}
}
if(name.equals(names[count])) will work only if the name user is searching is at the current index of names. So you have to check every item in the array to determine whether it exists in the array. You can do this:
int itemIndex = Arrays.asList(names).indexOf(name);
if(itemIndex>=0) // instead of if(name.equals(names[count]))
{
// rest of the codes; use the itemIndex to retrieve other information
}
else
{
System.out.println(name + " was not found");
}
Or manually loop over the names array as others showed.
System.out.println("Please enter a name to see matched information");
String name = ui.next();
for(int i = 0; i <names.length;i++){
if(name.equals(names[i]))
{
System.out.println("Name: "+names[i]+"\nAddress: "+address[i]+"\nPhone: "+phone[i]);
}
}
It seems like you have data input already done.
As for data retrieval by searching, if you don't care about efficiency, then you could iterate over the entire array to see if the text inputted matches any element in your array using
int searchIndex = 0;
for (int i = 0; i < names.length; i++) {
if (searchString.equals(names[i])) {
searchIndex = i;
}
}
where searchString would be the string input by the user to find the element in the array. The code block above assumes you don't have duplicate data, but you could easily tweak the returned index to contain an array of indexes that contain your data, if you wish. You'd then have an index number (or index numbers) with which you could use to find the rest of the data in your other arrays.

Categories