Java string sorting - java

This is no homework.Its an exercise I came across in a book.
Build a class named Name which represents the name of a person.The class should have fields that represent first name ,last name ,and fathersname.
The class should have these methods :
public Name (String fn,String f_n,String ln)
/* initializes the fields of an object with the values fn,f_n and m.
fn means first name
ln means last name
f_n means fathersname btw. */
public String getNormalOrder(); //returns the name of the person in the normal order : first name,fathers name,last name.
public String getReverseOrder(); //returns the name of the person in the reverse order : last name,fathers name,first name.
public boolean compare (String fn,String f_n,String ln); // Returns true if the first name is the same with fn,fathers name is the same with f_n, last name with ln.If the opposite happens it returns false.
Build a program named TestName which tests the methods of the class Firstname.
My solution
public class Name {
String fn;
String f_n;
String ln;
public Name(String initialfn, String initialf_n, String initialln) {
fn = initialfn;
f_n = initialf_n;
ln = initialln;
}
public String getNormalOrder() {
return fn + " " + f_n +
" " + ln;
}
public String getReverseOrder() {
return ln + ", " + f_n +
" " + fn + " ";
}
}
How about the third method which is comparing? Also how do I test the class?

For a flexible solution:
public enum NameMember {
FIRSTNAME, SECONDNAME, FATHERSNAME;
}
The Name class:
public class Name {
private final String firstName;
private final String secondName;
private final String fathersName;
public Name(String firstName, String secondName, String fathersName) {
this.firstName = firstName;
this.secondName = secondName;
this.fathersName = fathersName;
}
public String getName(NameMember member1, NameMember member2, NameMember member3) {
StringBuilder sb = new StringBuilder();
return sb.append(getMember(member1)).append(" ")
.append(getMember(member2)).append(" ")
.append(getMember(member3)).toString();
}
public String getMember(NameMember member) {
switch (member) {
case FIRSTNAME:
return firstName;
case SECONDNAME:
return secondName;
case FATHERSNAME:
return fathersName;
default:
return null;
}
}
#Override
public String toString() {
return getName(NameMember.FIRSTNAME, NameMember.SECONDNAME, NameMember.FATHERSNAME);
}
}
A NameComparator (flexible) class:
import java.util.Comparator;
public class NameComparator implements Comparator<Name> {
private NameMember nameMember;
public NameComparator(NameMember nameMember) {
this.nameMember = nameMember;
}
#Override
public int compare(Name name1, Name name2) {
return name1.getMember(nameMember).compareTo(name2.getMember(nameMember));
}
}
And the main class (test drive):
public static void main(String args[]) {
List<Name> names = new ArrayList<>();
names.add(new Name("Alice", "Burda", "Christophe"));
names.add(new Name("Ben", "Ashton", "Caine"));
names.add(new Name("Chane", "Bagwell", "Alex"));
names.add(new Name("Ann", "Clinton", "Brad"));
System.out.println("NAMES ORDERED BY FIRST NAME:");
Collections.sort(names, new NameComparator(NameMember.FIRSTNAME));
printNames(names);
System.out.println("\nNAMES ORDERED BY SECOND NAME:");
Collections.sort(names, new NameComparator(NameMember.SECONDNAME));
printNames(names);
System.out.println("\nNAMES ORDERED BY FATHERSNAME:");
Collections.sort(names, new NameComparator(NameMember.FATHERSNAME));
printNames(names);
}
private static void printNames(Collection<Name> names) {
names.stream().forEach(System.out::println);
}

Related

How can i change "Curso" class to print in other class?

I got 2 classes
class Curso{
private String name;
public Curso(String nome){
this.name = nome;
}
public String getName(){
return this.name;
}
}
and
public class testaCurso{
public static void main(String[] args){
Course c1 = new Course("Computer Science");
c1.addDisciplina("AlgProgII");
c1.addDisciplina("SO");
c1.addDisciplina ("Grafos");
System.out.println(c1);
}
}
i gotta modify the Course class so that it can store the names of the Disciplina that make up the course and work for the test above with the output as shown. Consider that a course will not have a maximum of 50 subjects.
output:
Course: Computer Science,
Disciplinas:{ AlgProgII SO Grafos }
class Curso {
private String name;
// Add an list field containg the disciplinas
private final List<String> disciplinas = new ArrayList<>();
public Curso(String name){
this.name = name;
}
public String getName(){
return this.name;
}
// Add a `addDisciplina` method
public void addDisciplina(String name) {
disciplinas.add(name);
}
// Override the `toString` method
#Override
public String toString() {
return "Course: " + name + ", Disciplinas: + ", disciplinas;
}
}
We can implement toString() like the following:
public class Course {
private final String name;
private final List<String> disciplinas;
public Course(String name){
this.name = name;
this.disciplinas = new ArrayList<>();
}
public Course(String name, List<String> disciplinas){
this.name = name;
this.disciplinas = new ArrayList<>(disciplinas);
}
public void addDisciplinas(String discplina){
this.disciplinas.add(discplina);
}
#Override
public String toString() {
return "Course: " + name + ", Disciplinas: {" + disciplinas.stream().collect(Collectors.joining(" ")) +"}";
}
}
Usage:
Course course = new Course("Computer Science", Arrays.asList("AlgProgII", "SO", "Grafos"));
System.out.println(course);
Output:
Course: Computer Science, Disciplinas: {AlgProgII SO Grafos}

How to output complete details

I am looking to create a leisure centre booking system in Java, which utilises OOP.
2 of the classes collect names and addresses and membership type, which are added to an ArrayList called memberRegister. How can I print all of the member details (i.e. what is stored in the array list), thus outputting Name, Address, Membertype, etc, all in one command?
My source code for classes in question follows...
public class Name {
private String firstName;
private String middleName;
private String lastName;
//constructor to create object with a first and last name
public Name(String fName, String lName) {
firstName = fName;
middleName = "";
lastName = lName;
}
//constructor to create object with first, middle and last name
//if there isn't a middle name, that parameter could be an empty String
public Name(String fName, String mName, String lName) {
firstName = fName;
middleName = mName;
lastName = lName;
}
// constructor to create name from full name
// in the format first name then space then last name
// or first name then space then middle name then space then last name
public Name (String fullName) {
int spacePos1 = fullName.indexOf(' ');
firstName = fullName.substring(0, spacePos1);
int spacePos2 = fullName.lastIndexOf(' ');
if (spacePos1 == spacePos2)
middleName = "";
else
middleName = fullName.substring(spacePos1+1, spacePos2);
lastName = fullName.substring(spacePos2 + 1);
}
// returns the first name
public String getFirstName() {return firstName; }
// returns the last name
public String getLastName() {return lastName; }
//change the last name to the value provided in the parameter
public void setLastName(String ln) {
lastName = ln;
}
//returns the first name then a space then the last name
public String getFirstAndLastName() {
return firstName + " " + lastName;
}
// returns the last name followed by a comma and a space
// then the first name
public String getLastCommaFirst() {
return lastName + ", "+ firstName;
}
public String getFullname() {
return firstName + " " + middleName + " " + lastName;
}
}
public class Address {
private String first_line, town, postcode;
public Address(String first_line, String town, String pcode)
{
this.first_line = first_line;
this.town = town;
postcode = pcode;
}
public Address()
{
first_line = "";
town = "";
postcode = "";
}
public String getFirst_line() {
return first_line;
}
public void setFirst_line(String first_line) {
this.first_line = first_line;
}
public String getTown() {
return town;
}
public void setTown() {
this.town = town;
}
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
}
public class Member extends Person {
private String id; // membership ID number
private String type; // full, family, exercise, swim, casual
public Member(String id, String type, Name n, Address a)
{
super(n, a);
this.id = id;
this.type = type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
import java.util.ArrayList;
public class Registration {
private ArrayList<Member> memberRegister;
public Registration()
{
memberRegister = new ArrayList();
}
public void register(Member m)
{
memberRegister.add(m);
}
public int countMembers()
{
return memberRegister.size();
}
public Member getMember(int i) {
return memberRegister.get(i);
}
public class Main {
public static void main(String[] args) {
Name n = new Name("Kieran", "David", "Nock");
Address a = new Address ("123 Skywalker Way", "London", "NW1 1AA");
Member m = new Member("001", "Full", n, a);
Registration reg = new Registration();
reg.register(m);
System.out.println(reg.countMembers());
System.out.println(reg.getMember(0).getName().getFullname());
}
}
Hey I would do it in following way
First override toString() methods of all the model classes and remember to override Member class toString() in following way
#Override
public String toString() {
return "Member{" +
"id='" + id + '\'' +
", type='" + type + '\'' +
'}'+super.toString();
}
After this adding the below single line in main method would work
reg.getMemberRegister().stream().forEach(System.out::println);
NOTE: create a getter for memberRegister list which is present in Registration Class

Non-Static variable while calling a constructor

I'm working on my code, to call some constructors from classes I created.
I'm sorry if my question is easy, but I tried to search everywhere and didn't figure out the answer.
On the other hand, all my classes are working well without any error.
When I need to call the constructor from the main class, it's giving me an error.
non-static variable this cannot be referred from a static context.
I will just post the first class I'm calling and having an error.
public class Test1 {
static int nextPers = 1;
public class Person{
private int persID;
private String persName;
private String email;
Person(int persID, String persName, String email){
persID = nextPers;
nextPers++;
this.persName = persName;
this.email = email;
}
public static void main(String [] args){
Person per = new Person(1 , "Raphael" , "meh#hotmail.com");
}
}
I cannot continue, the program is asking me to put static variables, and I cannot figure my error because when I write static before the variable, it's creating another error.
Your class Person is an inner class of Test1.
Move it to its own file or add the static keyword, like so:
public class Test1 {
public static class Person {
// your fields
}
}
I suggest reading up this other answer for a detailed explanation.
You should have a static counter for ID and not give it into constructor
public class Person {
private int persID;
private String persName;
private String email;
private static int nextPers = 0;
Person(String persName, String email){
this.persID = nextPers;
nextPers++;
this.persName = persName;
this.email = email;
}
public static void main(String [] args){
Person per = new Person("P0" , "p0#hotmail.com");
System.out.println(per.persID + " " + per.email + " " + per.persName);
per = new Person("P1" , "p1#hotmail.com");
System.out.println(per.persID + " " + per.email + " " + per.persName);
per = new Person("P2" , "p2#hotmail.com");
System.out.println(per.persID + " " + per.email + " " + per.persName);
}
}
nextPers must be a static class member, like
public class Person {
private static int nextPers = 0;
private int persID;
private String persName;
private String email;
Person(String persName, String email) {
this.persID = nextPers++;
this.persName = persName;
this.email = email;
}
}
(In your original code you are assigning nextPers to the persId argument, which I assume isn't what you really want, as it masks your instance variable with the same name.)
Place your Person class outside and you do not need to persId into your constructor.
package com.test;
class Person{
private int persID;
private String persName;
private String email;
Person( String persName, String email){
this.persID = Test.nextPers;// Whenever your constructor is invoked it will assign nextPers to persId
this.persName = persName;
this.email = email;
Test.nextPers++;// finally increment here
}
public int getPersID()
{
return persID;
}
public void setPersID( int persID )
{
this.persID = persID;
}
public String getPersName()
{
return persName;
}
public void setPersName( String persName )
{
this.persName = persName;
}
public String getEmail()
{
return email;
}
public void setEmail( String email )
{
this.email = email;
}
#Override
public String toString()
{
return "Person [persID=" + persID + ", persName=" + persName + ", email=" + email + "]";
}
}
public class Test
{
static int nextPers = 1;
public static void main( String[] args )
{
Person person1 = new Person("Raphael" , "meh#hotmail.com");
System.out.println( person1 );
Person person2 = new Person("Man" , "man#hotmail.com");
System.out.println( person2 );
}
}
Output
Person [persID=1, persName=Raphael, email=meh#hotmail.com]
Person [persID=2, persName=Man, email=man#hotmail.com]

how to sort name by last name from command line in java

I am trying to write a program which sorts name by it's last name, first name when "sort" condition is applied. The input will be provided from command line. I have started this way but have no idea how to make it work.
Input: sort "john main" "rob class" "bob ram"
Output: class,rob main,john ram,bob
public static void main(String[] args)
{
String[] args_name = new String[args.length-1];
System.arraycopy(args, 1, args_name, 0, args.length-1);
if(args[0].equals("sort"))
{
String firstName = name.substring(args_name,name.indexOf(" "));
String lastName = name.substring(name.indexOf(" ")+1);
String slst = lastName + ", " + firstName;
Arrays.sort(slst);
for (String s: slst) System.out.print(s);
}
}
Try using a Comparator to sort your input. I removed your args-related code for the sake of simplicity. You will still need to re-add it properly.
Required Imports
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
The Name
class Name{
public static final String FULL_NAME_DELIMITER = " ";
public static final String PRINT_DELIMITER = ", ";
private String firstName;
private String lastName;
public Name(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
}
public static String[] getName(String fullName){
return fullName.split(FULL_NAME_DELIMITER);
}
public String getLastName(){
return this.lastName;
}
#Override
public String toString(){
return String.join(PRINT_DELIMITER , this.lastName, this.firstName);
}
public void print(){
System.out.println(this);
}
}
The Comparator
class NameComparator implements Comparator<Name>{
#Override
public int compare(Name a, Name b) {
return a.getLastName().compareTo(b.getLastName()); // ASC: a to b or DESC: b to a
}
}
Usage
public class Main {
// Holds the sorted names
private static List<Name> names = new ArrayList<>();
public static void main(String[] args) {
// The input names
String[] input = new String[]{
"john main",
"rob class",
"bob ram"
};
// Prepare list for sorting
String firstName;
String lastName;
String[] completeName;
for (String fullName : input) {
completeName = Name.getName(fullName);
firstName = completeName[0];
lastName = completeName[1];
names.add(new Name(firstName, lastName));
}
// Actually sort
names.sort(new NameComparator());
// Print
names.forEach(System.out::println);
}
}
EDIT
To use the input from the command line, the args parameter is what you want to use.
Usage with Commandline Input
public class Main {
// Holds the sorted names
private static List<Name> names = new ArrayList<>();
public static void main(String[] args) {
// The method (in case something else than "sort" is desired)
String method = args[0];
// Check for valid method
if(!method.equals("sort")) return;
// The input names
String[] input = Arrays.copyOfRange(args, 1, args.length);
// Prepare list for sorting
String firstName;
String lastName;
String[] completeName;
for (String fullName : input) {
completeName = Name.getName(fullName);
firstName = completeName[0];
lastName = completeName[1];
names.add(new Name(firstName, lastName));
}
// Actually sort
names.sort(new NameComparator());
// Print
names.forEach(System.out::println);
}
}
EDIT 2
To use the first name instead of the last name, simply alter the Comparator.
class NameComparator implements Comparator<Name>{
#Override
public int compare(Name a, Name b) {
return a.getFirstName().compareTo(b.getFirstName()); // ASC: a to b or DESC: b to a
}
}
Of course, you would need to adjust the Name class as well, by adding:
public String getFirstName(){
return this.firstName;
}
if i understand your question well here is my code that solving this problem
public static void shortName(String shortName){
System.out.println("please enter yout name : ");
Scanner scanner = new Scanner(System.in);
String fullName = scanner.nextLine();
if( shortName.equals("sort")){
String [] nameArr = fullName.split(" ");
int lastNameIndex = nameArr.length - 1;
String name = nameArr[0] +" "+ nameArr[lastNameIndex];
System.out.println("welcome : "+name);
}
else {
System.out.println("welcome : "+fullName);
}
}
public static void main(String[] args) {
shortName("sort");
}

NullPointerException when adding Object to ArrayList

I'm very new to Java and have been trying to set-up an ArrayList CustomerList that takes object Customer, where Customer has attributes from class IAddress. When calling the .add method in my main code however, I am given a NullPointerException error, which I assume is being given because my method isn't receiving anything to add to the ArrayList. I thought it was an issue with the attributes being initialised to empty strings, but when editing them to contain some information, the error still occured.
The ArrayList CustomerList
public class CustomerList {
public ArrayList<Customer> Clients;
public CustomerList() {
Clients = new ArrayList<>();
}
public void add(Customer src) {
Clients.add(src);
}
public void remove(Customer src) {
Clients.remove(src);
}
public void Display(JTextArea jClientsTextArea) {
for (int i = 0; i < Clients.size(); i++) {
Clients.get(i).Display(jClientsTextArea);
}
}
}
Receives Customer from this class
public class Customer {
private String FirstName;
private String Surname;
private IAddress HomeAddress;
public String DOB;
public Customer() {
FirstName = "";
Surname = "";
DOB = "01/01/1900";
HomeAddress = new IAddress();
public void Display(javax.swing.JTextArea jAddressTextArea) {
jAddressTextArea.setLineWrap(true);
jAddressTextArea.append("First Name: " + FirstName + "\n");
jAddressTextArea.append("Surname: " + Surname + "\n");
jAddressTextArea.append("DOB:" + DOB + "\n");
jAddressTextArea.append("Street: " + HomeAddress.getStreet() + "\n");
jAddressTextArea.append("House Name: " + HomeAddress.getHouseName() + "\n");
jAddressTextArea.append("House Number: " + HomeAddress.getHouseNo() + "\n");
jAddressTextArea.append("Area: " + HomeAddress.getArea() + "\n");
jAddressTextArea.append("Postcode: " + HomeAddress.getPostCode() + "\n");
jAddressTextArea.append("Town: " + HomeAddress.getTown() + "\n");
jAddressTextArea.append("Country: " + HomeAddress.getCountry() + "\n");
}
public void Edit(String strfirstname, String strsurname, String strDOB, String strStreet, String strHouseName, String strHouseNo, String strHouseArea, String strPostCode, String strTown, String strCountry) {
FirstName = strfirstname;
Surname = strsurname;
DOB = strDOB;
HomeAddress.setStreet(strStreet);
HomeAddress.setHouseName(strHouseName);
HomeAddress.setHouseNo(strHouseNo);
HomeAddress.setArea(strHouseArea);
HomeAddress.setPostCode(strPostCode);
HomeAddress.setTown(strTown);
HomeAddress.setCountry(strCountry);
}
}
Which receives attributes from IAddress
public class IAddress {
private String Name;
private String Street;
private String HouseNo;
private String HouseName;
private String Area;
private String PostCode;
private String Town;
private String Country;
public IAddress() {
Name = "";
Street = "";
HouseNo = "";
HouseName = "";
Area = "";
PostCode = "";
Town = "";
Country = "";
}
public void setName(String strName) {
Name = strName;
}
public void setStreet(String strStreet) {
Street = strStreet;
}
public void setHouseNo(String strHouseNo) {
HouseNo = strHouseNo;
}
public void setHouseName(String strHouseName) {
HouseName = strHouseName;
}
public void setArea(String strArea) {
Area = strArea;
}
public void setPostCode(String strPostCode) {
PostCode = strPostCode;
}
public void setTown(String strTown) {
Town = strTown;
}
public void setCountry(String strCountry) {
Country = strCountry;
}
}
I've been banging my head against this problem for hours and am ready for it to be something stupidly simple. Thank you.
In your code above the only reason why calling myCustomerList.add(...) could throw is that myCustomerList itself is null. This is because the Clients inside it is initialized in the constructor, and never set to null again. The value of src does not matter as well - the call to Clients.add(src) would succeed even if src is null.
You need to make sure that in your main you do initialize your customer list, like this:
CustomerList list = new CustomerList();

Categories