Printing separate name variations in java? - java

I am making a programming to print the following
user inputs name like so --> first middle last
prints:
FML
Variation one: LAST, First M.
Variation two: Last, First Middle
Now, I need an if statement so that if just a first name is entered it says "error, incorrect input"
I coded this horribly and extremely unconventional, but hey, this is the first thing I've ever programmed before, so I guess we all start somewhere.
import java.util.Scanner;
public class name {
public static void main(String[]args)
{
Scanner input = new Scanner(System.in);
String fullName = input.nextLine();
String firstName;
String middleName;
String lastName;
//Declares length of entire name
int nameLength = fullName.length();
//Declares int where first space is
int a = fullName.indexOf(" ");
//Declares int where second space is
int b = fullName.lastIndexOf(" ");
//If they equal each other, then there is only one space
if ( a == b )
{
firstName = fullName.substring(0,a);
lastName = fullName.substring(a+1,nameLength);
String firstNameInitial = firstName.substring(0,1);
String lastNameInitial = lastName.substring(0,1);
String upperCaseInitials = (firstNameInitial.toUpperCase() + lastNameInitial.toUpperCase());
firstName = fullName.substring(0,a);
lastName = fullName.substring(b+1,nameLength);
System.out.println("Your initials are: " + upperCaseInitials);
System.out.println("Variation One: " + lastName.toUpperCase() + ", " + firstNameInitial.toUpperCase() + firstName.substring(1,a));
System.out.println("Variation Two: " + lastNameInitial.toUpperCase() + lastName.substring(1,lastName.length()) + ", " + firstNameInitial.toUpperCase() + firstName.substring(1,a));
}
//If a < b then it will notice a middle name exists due to multiple spaces
else if ( a < b )
{
firstName = fullName.substring(0,a);
middleName = fullName.substring(a+1,b);
lastName = fullName.substring(b+1,nameLength);
String firstNameInitial = firstName.substring(0,1);
String middleNameInitial = middleName.substring(0,1);
String lastNameInitial = lastName.substring(0,1);
String upperCaseInitials = (firstNameInitial.toUpperCase() + middleNameInitial.toUpperCase() + lastNameInitial.toUpperCase());
//MNIC = Middle Name Initial Capitalized
String MNIC = middleNameInitial.toUpperCase();
//MNIMFC = Middle Name Initial Minus First Character
String MNIMFC = middleName.substring(1, middleName.length());
System.out.println("Your initials are: " + upperCaseInitials);
System.out.println("Variation One: " + lastName.toUpperCase() + ", " + firstNameInitial.toUpperCase() + firstName.substring(1,a) + " " + middleNameInitial.toUpperCase() + "." );
System.out.println("Variation Two: " + lastNameInitial.toUpperCase() + lastName.substring(1,lastName.length()) + ", " + firstNameInitial.toUpperCase() + firstName.substring(1,a) + " " + MNIC + MNIMFC);
}
}
}

You can use the String.split() function to split a String into its parts along a seperator.
In your case that would be the space (" ")
Try:
Scanner input = new Scanner(System.in);
String fullName = input.nextLine();
String firstName;
String middleName;
String lastName;
String[] parts = fullName.split(" ");
if(parts.length() == 3){
// 3 words were entered, so there is a middle name
}
// ...

You can just add this check
if(fullName.indexOf(" ")==-1 || (fullName.indexOf(" ") == fullName.lastIndexOf(" "))){
// The first check is to check if only firstname was given and the second check is to check if only first and middle names were given.
// If first + middle is a valid scenario, you can remove the second half of the if condition
System.out.println("error, incorrect input");
System.exit(0);
}
before the below statement in your code.
int nameLength = fullName.length();

You can simply check for a == -1. indexOf returns -1 if not found (as per the docs).
if (a == -1)
System.out.println("Error, invalid input!");
else if (a == b)
...

You can narrow down to the condition you stated by following these steps:
Trim the input String fullName before statement int a = fullName.indexOf(" ");
Next check if the index of whitespace (i.e. value of a and b variables) is -1, then you can assume that the input contains only a single word, presumably Firstname
Print the error message "error, incorrect input"

since it's your first attempt, I'll give you a modified version of your code:
public class name {
public static void main(String[]args)
{
Scanner input = new Scanner(System.in);
String fullName = input.nextLine();
String firstName;
String middleName;
String lastName;
//Declares length of entire name
int nameLength = fullName.length();
//Declares int where first space is
int a = fullName.indexOf(" ");
//Declares int where second space is
int b = fullName.lastIndexOf(" ");
/*** Use the split function to split the names with spaces as delimiter **/
String[] n = fullName.split(' ');
firstName = n[0];
if( n.length == 2 ) {
lastName = n[1];
}
if( n.length > 3 ) {
lastName = n[1];
middleName = n[2];
}
String firstNameInitial = firstName.substring(0,1);
String middleNameInitial = middleName.substring(0,1);
String lastNameInitial = lastName.substring(0,1);
String upperCaseInitials = (firstNameInitial.toUpperCase() + middleNameInitial.toUpperCase() + lastNameInitial.toUpperCase());
//MNIC = Middle Name Initial Capitalized
String MNIC = middleNameInitial.toUpperCase();
//MNIMFC = Middle Name Initial Minus First Character
String MNIMFC = middleName.substring(1, middleName.length());
System.out.println("Your initials are: " + upperCaseInitials);
System.out.println("Variation One: " + lastName.toUpperCase() + ", " + firstNameInitial.toUpperCase() + firstName.substring(1,a) + " " + middleNameInitial.toUpperCase() + "." );
System.out.println("Variation Two: " + lastNameInitial.toUpperCase() + lastName.substring(1,lastName.length()) + ", " + firstNameInitial.toUpperCase() + firstName.substring(1,a) + " " + MNIC + MNIMFC);
}
}

Related

Why am I getting 2 errors when I try to run this code relating to string manipulation and if/else statements, this is in java btw, ty [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
Setting up the 2 user inputted phrases
Scanner input = new Scanner(System.in);
System.out.println("Enter any phrase: ");
String userPhrase1 = input.nextLine();
System.out.println("Enter another phrase: ");
String userPhrase2 = input.nextLine();
//The if/else statements for if the phrases are the same or different
if (userPhrase1.equals(userPhrase2) == true)
{
String SameOrDif = "\n" + "Both phrases are the same and";
}
else
{
String SameOrDif = "\n" + "Both phrases are different and";
}
//The if/else statements for the phrase lengths
if (userPhrase1.length() - userPhrase2.length() == 0)
{
String stringLength = "the phrases are equal in length";
}
else if ((userPhrase1.length() - userPhrase2.length()) > 0)
{
String stringLength = "the first phrase '" + userPhrase1 + "' is longer than the second phrase '"
+ userPhrase2 + "'";
}
else
{
String stringLength = "the second phrase '" + userPhrase2 + "' is longer than the first phrase '"
+ userPhrase1 + "'";
}
//This is where I get the errors from
System.out.println(SameOrDif + stringLength + ", and the amount of characters before the first
space in the first phrase is " + userPhrase1.indexOf("o") + "and " + userPhrase2.indexOf("k") + "
for the second phrase");
}
}
You are getting an error because the variables SameOrDif and stringlength are not within the scope. You must declare them outside the if statements.
Also: You are not printing properly. Like, you are not using + operators correctly.
import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter any phrase: ");
String userPhrase1 = input.nextLine();
System.out.println("Enter another phrase: ");
String userPhrase2 = input.nextLine();
String SameOrDif="";
String stringLength="";
if (userPhrase1.equals(userPhrase2) == true)
{
SameOrDif = "\n" + "Both phrases are the same and";
}
else
{
SameOrDif = "\n" + "Both phrases are different and";
}
if (userPhrase1.length() - userPhrase2.length() == 0)
{
stringLength = "the phrases are equal in length";
}
else if ((userPhrase1.length() - userPhrase2.length()) > 0)
{
stringLength = "the first phrase '" + userPhrase1 + "' is longer than the second phrase '"
+ userPhrase2 + "'";
}
else
{
stringLength = "the second phrase '" + userPhrase2 + "' is longer than the first phrase '"
+ userPhrase1 + "'";
}
System.out.println(SameOrDif + stringLength + ", and the amount of characters before the first
space in the first phrase is " + userPhrase1.indexOf("o") + "and " + userPhrase2.indexOf("k") +
"for the second phrase");
}
}

What is causing this StringIndexOutOfBoundsException?

I am writing a program that takes names from a text file and prints the initials of the names.
The names are in "Last, First M." format, with each name being on a separate line.
Because the text file contains the names of everybody in my class I am not including it in this post.
The error I am receiving is:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at java.lang.String.substring(String.java:1963)
at AS01a.main(AS01a.java:28)
/* My Name
** February 6, 2019
** Class Name
** Assignment Name
** Collaborations: None
*/
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class AS01a{
public static void main(String args[]) throws FileNotFoundException{
String DEFAULT_FILE_NAME = "AS01.txt";
String fileName;
if (args.length != 0)
{ fileName = args[0]; }
else
{ fileName = DEFAULT_FILE_NAME; }
Scanner input = new Scanner(new File(fileName));
String fullName, first, middle, last, initials;
while(input.hasNextLine()){
fullName = input.nextLine();
//Dividing the full name into individual initials
first = fullName.substring(fullName.indexOf(" ")+1, fullName.indexOf(" ")+2);
middle = fullName.substring(fullName.lastIndexOf(" ")+1, fullName.lastIndexOf(" ")+2);
last = fullName.substring(0,1);
//Testing to see if the full name contains a middle name
if(fullName.indexOf(" ") == fullName.lastIndexOf(" ")){
initials = first + ". " + last + ".";
}
else{
initials = first + ". " + middle + ". " + last + ".";
}
if(input.hasNextLine()){
System.out.println(fullName + " yields " + initials);
}
}
}
}
My results come out as expected, the only problem is the errors previously mentioned.
Your StringIndexOutOfBoundsException may be due to the data your receiving as we do not know the "Full Name". If someone doesn't have a first/middle/last name you will get the exception because you are not checking for this before the first middle and last are initialized. Move your initializers into your if statements and see if that helps.
Try this.
while(input.hasNextLine()){
fullName = input.nextLine();
if(fullName.isEmpty())
fullName = input.nextLine();
//Testing to see if the full name contains a middle name
if(fullName.indexOf(" ") == fullName.lastIndexOf(" ")){
first = fullName.substring(fullName.indexOf(" ")+1, fullName.indexOf(" ")+2);
last = fullName.substring(0,1);
initials = first + ". " + last + ".";
}
else{
first = fullName.substring(fullName.indexOf(" ")+1, fullName.indexOf(" ")+2);
middle = fullName.substring(fullName.lastIndexOf(" ")+1, fullName.lastIndexOf(" ")+2);
last = fullName.substring(0,1);
initials = first + ". " + middle + ". " + last + ".";
}
if(input.hasNextLine()){
System.out.println(fullName + " yields " + initials);
}
}
fullName seems to be an empty string, you can easily check this with debugger. And the reason why it's empty is that you probably have a blank line in your file. If it so, you should add empty check like if (fullName.isEmpty()) continue; to iterate over the remaining lines.

Beginner Java - Changing String from First Middle Last to Last, First Middle

Trying to work out a homework problem that demands:
Changes a name so that the last name comes first.
Example: "Mary Jane Lee" will return "Lee, Mary Jane".
If name has no spaces, it is returned without change.
After doing some research it seems I can do this with the Split method, but we've not learned that yet.
The thing is I've worked out the code and it seems to work when spaces
and a full name is entered, but when there's no middle name or no spaces to separate the character, I get the error:
when the name entered is simply: Harry Smith
java.lang.StringIndexOutOfBoundsException: String index out of range: -7
and
java.lang.StringIndexOutOfBoundsException: String index out of range: -1
when the name is Sarah
This is my code, but I'm not sure how to fix it:
public class Names {
public static String lastNameFirst(String name) {
int firstIndex = name.indexOf(" ");
int secondIndex = name.indexOf(" ", firstIndex + 1);
String firstName = name.substring(0, name.indexOf(" "));
String middleName = name.substring(firstIndex + 1, secondIndex);
String lastName = name.substring(secondIndex + 1);
String result = "";
result = lastName + ", " + firstName + " " + middleName;
return result;
}
}
Thanks in advance!!
using split and a switch would be a lot easier
String name = "Mary Jane Lee";
String arr[] = name.split (" ");
switch (arr.length) {
case 1:
System.out.println(name);
break;
case 2:
System.out.println(arr[1] + ", " + arr[0]);
break;
default:
System.out.println(arr[2] + ", " + arr[0] + " " + arr[1]);
}
A more robust way is to use lastIndexOf to find the last space:
int lastSpace = name.lastIndexOf(' ');
if (lastSpace != -1) {
String lastName = name.substring(lastSpace + 1);
String partBeforeLastName = name.substring(0, lastSpace);
return lastName + ", " + partBeforeLastName;
} else {
return name;
}
You don't actually really care about the other space (if it's there at all), since the first and middle names stay in the same relative order.
(Generally, there are lots of falsehoods that programmers believe about names; but let's put those aside for the purpose of the exercise.)
Your code assumes that the input String contains at least two spaces. When that assumption is wrong (as in the inputs "Harry Smith" and "Sarah"), you get an exception.
You must check whether firstIndex and secondIndex are positive before using their values.
The problem is that your code excepts that there are 3 names. It does not handle when there are less names.
public static String lastNameFirst(String name)
{
int firstIndex = name.indexOf(" ");
if ( firstIndex >= 0 )
{
int secondIndex = name.indexOf(" ", firstIndex + 1 );
String firstName = name.substring(0, firstIndex);
if ( secondIndex >= 0 ) // we have 3 names
{
String middleName = name.substring(firstIndex + 1, secondIndex);
String lastName = name.substring(secondIndex + 1);
return lastName + ", " + firstName + " " + middleName;
}
else // we have 2 names
{
String lastName = name.substring(firstIndex + 1);
return lastName + ", " + firstName;
}
}
else // have only one name
return name;
}
Should worth trying lastIndexOf(), too:
public static String lastNameFirst(String name)
{
int lastIndex = name.lastIndexOf(" ");
if ( lastIndex >= 0 ) // have at least 2 names
{
String firstNames = name.substring(0,lastIndex);
String lastName = name.substring(lastIndex + 1);
return lastName + ", " + firstNames;
}
}
else // have only one name
return name;
}
Also, could try a different approach, split the name into an array, something like this:
public static String lastNameFirst(String name)
{
String[] parts = name.split(" ");
switch ( parts.length )
{
case 1:
return name;
case 2:
return parts[1] + ", " + parts[0];
case 3:
return parts[2] + ", " + parts[0] + " " + parts[1];
}
}

I'm trying to write a Java method that will format a name to Last, First M. ... for any amount of middle names

String nameStr = "george raymond richard martin";
String formattedName = " ", firstName = " ", middleName = " ", lastName = " ", middleInitial = " ";
int index = 0;
if (nameStr.indexOf(" ") == -1) { //for one name case
formattedName = nameStr.substring(0, 1).toUpperCase().substring(1).toLowerCase();
}
if (nameStr.indexOf(" ") != -1) {
String nameParts[] = nameStr.split(" ");
int N = nameParts.length;
if (N == 2) { //if there are just two names
firstName = nameParts[0];
lastName = nameParts[N - 1];
firstName = firstName.substring(0, 1).toUpperCase().substring(1).toLowerCase();
lastName = lastName.substring(0, 1).toUpperCase().substring(1).toLowerCase();
formattedName = lastName + ", " + firstName;
} else { //for any amount of names
for (index = 1; index <= N - 2; index++) {
middleName = nameParts[index];
firstName = nameParts[0];
lastName = nameParts[N - 1];
middleInitial = middleName.substring(0, 1).toUpperCase() + ".";
formattedName = lastName + ", " + firstName + middleInitial;
}
}
}
System.out.println(formattedName);
this is what I have right now, and I feel like my logic is on the right track but it's not printing anything out properly. It doesn't print for the one word case, and for the two word case it just prints out the comma. The case for any amount of middle names works, but only for three words, and if there is more than one middle name it just truncates it to the last middle name.
I have no idea what the issue is, I just feel like i need someone else to look at it. Thanks :)
I think what you need is the String#split(String) method. If the full name is a String of space-separated words, split will make quick work of your problem.
I assume that you want "George Raymond Richard Martin" to come out as "George R. R. Martin" because... well, that's what he goes by. Otherwise, you haven't really told us what the specs are, but this is how you'd accomplish that.
String toShortenedName(String fullName) {
assert(fullName != null); // :P
// Split the fullName where there are 1-or-more whitespaces.
String[] nameParts = fullName.trim().split("\\s+");
// We'll be building our return value with this.
StringBuilder nameBuilder = new StringBuilder();
for (int i = 0; i < nameParts.length; i++) {
if (i > 0) {
// Not the first iteration; add a space to what came before.
nameBuilder.append(' ');
}
String part = nameParts[i];
if (i == 0 || i == nameParts.length - 1) {
// first or last name
nameBuilder.append(part);
} else {
char middleInitial = part.charAt(0);
nameBuilder.append(String.format("%c.", middleInitial));
}
}
return nameBuilder.toString();
}
formattedName=nameStr.substring(0,1).toUpperCase().substring(1).toLowerCase()
So, first you take the first letter from string nameStr and convert it to upperCase. What you do next (substring(1)) is actually substringing that single letter you took, not the whole previous string. You need to first convert that single letter to upperCase, and then in another line append the rest of the original string to your new string. Something like this:
formattedName = nameStr.substring(0,1).toUpperCase();
formattedName += nameStr.substring(1).toLowerCase();
This is your code slightly updated :
// TODO Auto-generated method stub
//String nameStr = "george raymond richard martin";
String nameStr = "Pablo Diego José Francisco de Paula Juan Nepomuceno María de los Remedios Cipriano de la Santísima Trinidad Ruiz y Picasso";
String formattedName = " ", firstName = " ", middleName = " ", lastName = " ", middleInitial = " ";
int index=0;
if(nameStr.indexOf(" ") == -1){ //for one name case
formattedName = nameStr.substring(0,1).toUpperCase().substring(1).toLowerCase();
}
if(nameStr.indexOf(" ") != -1){
String nameParts [] = nameStr.split(" ");
int N = nameParts.length;
firstName = nameParts[0];
lastName = nameParts[N-1];
if(N == 2){ //if there are just two names
firstName = nameParts[0];
lastName = nameParts[N-1];
firstName = firstName.substring(0,1).toUpperCase().substring(1).toLowerCase();
lastName = lastName.substring(0,1).toUpperCase().substring(1).toLowerCase();
formattedName = lastName + ", " + firstName;
}else{ //for any amount of names
for(index = 1; index<=N-2; index++){
middleName = nameParts[index];
middleInitial = middleInitial + middleName.substring(0, 1).toUpperCase()+ ".";
}
}
}
formattedName = lastName + ", " + firstName + middleInitial;
System.out.println(formattedName);
I send my solution. Maybe help you.
Output: Martin, George R.R.
String nameStr = "george raymond richard martin";
String firstName = " ", lastName = " ", middleInitial = " ";
StringBuilder formattedName=new StringBuilder();
StringBuilder nb=new StringBuilder();
String[] splitNames=(nameStr.split("\\s+"));
for(int i=0;i<splitNames.length;i++){
if(i>0 && i<splitNames.length-1) {
splitNames[i]=splitNames[i].substring(0,1).toUpperCase()+".";
nb.append(splitNames[i]);
}else{
splitNames[i]=splitNames[i].substring(0,1).toUpperCase()+splitNames[i].substring(1).toLowerCase();
}
}
firstName=splitNames[0];
lastName=splitNames[splitNames.length-1];
formattedName.append(lastName);
formattedName.append(", ");
formattedName.append(firstName+" ");
formattedName.append(nb);
System.out.println(formattedName.toString());

Null Pointer Exception Error, not sure why

So I had to create a method that separated input string into first/middle/last names, counted the number of "students" created, etc, and then I had to create a class that tested those methods.
public void setName(String newName)
{
String[] nameInput = newName.split(" ");
if(nameInput.length == 0)
{
System.out.println("Error, please enter at least two names.");
newName = null;
}
else if(nameInput.length == 1)
{
firstName = nameInput[0];
middleName = "";
lastName = nameInput[1];
newName = firstName + lastName;
}
else if(nameInput.length == 2)
{
firstName = nameInput[0];
middleName = nameInput[1];
lastName = nameInput[2];
newName = firstName + middleName + lastName;
}
else
{
System.out.println("Error! You can only enter up to three names.");
}
}
public String getName()
{
if (middleName == null)
{
return firstName + " " + lastName;
}
else
return firstName + " " + middleName + " " + lastName;
}
public String getId()
{
return identifier = generateID();
}
#Override
public String toString()
{
return getName() + "\n" + "(" + generateID() + ")";
}
private String generateID()
{
return UUID.randomUUID().toString();
}
and this is the way I am testing the code:
public static void testStudent()
{
System.out.println("Trying to create testStudent1 with a single name...");
testStudent1 = new Student("A");
System.out.println("testStudent1.toString() is " + testStudent1.toString());
System.out.println("testStudent1.getFirstName() is " + testStudent1.getFirstName());
System.out.println("testStudent1.getMiddleName() is " + testStudent1.getMiddleName());
System.out.println("testStudent1.getLastName() is " + testStudent1.getLastName());
System.out.println("Trying to create testStudent2 with two names...");
testStudent1 = new Student("A B");
System.out.println("testStudent2.toString() is " + testStudent2.toString());
System.out.println("testStudent2.getFirstName() is " + testStudent2.getFirstName());
System.out.println("testStudent2.getMiddleName() is " + testStudent2.getMiddleName());
System.out.println("testStudent2.getLastName() is " + testStudent2.getLastName());
System.out.println("Trying to create testStudent3 with three names...");
testStudent1 = new Student("A B C");
System.out.println("testStudent3.toString() is " + testStudent3.toString());
System.out.println("testStudent3.getFirstName() is " + testStudent3.getFirstName());
System.out.println("testStudent3.getMiddleName() is " + testStudent3.getMiddleName());
System.out.println("testStudent3.getLastName() is " + testStudent3.getLastName());
}
I keep running into a null pointer exceptions when it tests toString for a student with 2 names, and I have no clue why.
Edit: The issue is with the testStudent variable in the testStudent() method.
System.out.println("Trying to create testStudent1 with a single name...");
testStudent1 = new Student("A");
System.out.println("testStudent1.toString() is " + testStudent1.toString());
System.out.println("testStudent1.getFirstName() is " + testStudent1.getFirstName());
System.out.println("testStudent1.getMiddleName() is " + testStudent1.getMiddleName());
System.out.println("testStudent1.getLastName() is " + testStudent1.getLastName());
System.out.println("Trying to create testStudent2 with two names...");
Student testStudent2 = new Student("A B");
System.out.println("testStudent2.toString() is " + testStudent2.toString());
System.out.println("testStudent2.getFirstName() is " + testStudent2.getFirstName());
System.out.println("testStudent2.getMiddleName() is " + testStudent2.getMiddleName());
System.out.println("testStudent2.getLastName() is " + testStudent2.getLastName());
System.out.println("Trying to create testStudent3 with three names...");
Student testStudent3 = new Student("A B C");
System.out.println("testStudent3.toString() is " + testStudent3.toString());
System.out.println("testStudent3.getFirstName() is " + testStudent3.getFirstName());
System.out.println("testStudent3.getMiddleName() is " + testStudent3.getMiddleName());
System.out.println("testStudent3.getLastName() is " + testStudent3.getLastName());
Since you are re-using the testStudent1 variable to create a new Object of Student class and not using them to invoke getter functions, it will throw an NPE for testStudent2 and testStudent3 variables.
Answer for old issue: The issue is with your while statement. It will never stop.
You can just find out the count by doing nameInput.length for the String array.
It should be like this:
String[] nameInput = newName.split(" ");
if (nameInput.length == 1)
{
System.out.println("Error, please enter at least two names.");
newName = null;
}
else if (nameInput.length == 2)
{
...
}
else if (nameInput.length == 3)
{
...
}
else
{
...
}
You could use StringTokenizer class to help you with this.
import java.util.StringTokenizer
StringTokenizer test = new StringTokenizer("An example string");
while (test.hasMoreTokens()) {
System.out.println(test.nextToken());
}
Output:
An
example
string.
The countTokens() method can provide how many tokens a string will provide prior processing. That way you will know if you have a middle name or not.
please check trim() method
public static void getName(String newName) {
newName = newName.trim();
String fullName = null;
String[] nameInput = newName.split(" ");
switch (nameInput.length) {
case 2:
fullName = mergeName(nameInput[0], "", nameInput[1]);
break;
case 3:
fullName = mergeName(nameInput[0], nameInput[1], nameInput[2]);
break;
default:
System.out.println("Error, please enter at least two names.");
break;
}
System.out.println(fullName);
}
public static String mergeName(String firstName, String middleName,
String lastName) {
String name = firstName+" " + middleName+" " + lastName;
return name;
}

Categories

Resources