Use a Method in Java to find the Last name of any given name
I need to use a method to find out the last name of any given name - meaning given any full name as a parameter the method should return the last name.
Here is the code that I have written but which will not compile. Need help! Thanks in advance
class LastName {
public static void main(String[] args) {
getlastName(" ");
System.out.println();
}
public static String getlastName(String lastName) {
System.out.println("Enter your full name: ");
int firstSpace = fullName.indexOf(" ");
int middleSpace = fullName.middleIndexOf(" ");
lastName = fullName.substring(firstSpace,middleSpace);
return lastName;
}
}
.
Re: Use a Method in Java to find the Last name of any given name
Quote:
which will not compile
Use code tags
BB Code List - Java Programming Forums - The Java Community
... and copy-paste your compiler errors.
Re: Use a Method in Java to find the Last name of any given name
Quote:
given any full name as a parameter the method should return the last name.
What is the format for the full name?
last, first
last first
first last
first middle last
If the full name is in a String and you know what format it is in, the String class has several methods that would be useful: indexOf, substring and split for example.
Re: Use a Method in Java to find the Last name of any given name
The format for the full name is First, Middle, Last.
Thanks in advance.
Best Regards,
Re: Use a Method in Java to find the Last name of any given name
Look at the different versions of the indexOf method to scan to the second or last space.
Re: Use a Method in Java to find the Last name of any given name
getlastName(" "); is returning a String and where in your program you are trying to get the returned value?
If it's not even compiling, copy & paste the full description of errors here.