Two input files are provided that you can use to test the correctness of your program. However, your program must work correctly on any other file in the same format.
You must follow good programming practices (indentation, comments, useful variable names, etc).
Problem:
Given a list of names in a file in the format first last, sort names by last name, then by first name if last names are same. Write an efficient program to solve this problem. Print the names in sorted order.
Example:
Input file:
John Smith
Darian Johnson
Mary Little
Bob Johnson
Sorted names:
Johnson Bob
Johnson Darian
Little Mary
Smith John
/* Program */
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author
*/
public class NameSorter {
public static void main(String args[]) throws FileNotFoundException, IOException {
// Set file in to buffer
BufferedReader bfreader = new BufferedReader(new FileReader("E:\\input.txt"));
//Generic list of type String so you can add names in to this list for sorting
List<String> nameList = new ArrayList<String>();
// read file until last line of file
String nameLine = bfreader.readLine();
String splittedNameLine[] = new String[2];
while (nameLine != null) {
//spilt name so you can get the first and last name
splittedNameLine = nameLine.split(" ");
//add name in reverse order into list
nameList.add(splittedNameLine[1] + " " + splittedNameLine[0]);
nameLine = bfreader.readLine();
}
// sort your list
Collections.sort(nameList);
//print list using for eachloop
for (String name : nameList) {
System.out.println(name);
}
}
}
0 comments:
Post a Comment