awgeful
awgeful

Reputation: 71

How to print the first name and initials of a full name

I'm new to Java and I'm not sure on how to print the first name and initials when the user inputs their full name. For example, if the user inputs "john doe", it should print out "Greetings, John, your initials are JD"

import java.util.Scanner;
public class Test {
   public static void main(String[] args) {
     Scanner reader = new Scanner(System.in);
     System.out.print("Enter full name: ");
     String fullName = reader.nextLine();

     System.out.print("Greetings, " + getFirstName(fullName) + ", your initials are " + getInitials(fullName));
   }

   public static String getFirstName(String fullName) {
      return fullName.substring(0,1).toUpperCase() + fullName.substring(1).toLowerCase();
   }
   
   public static String getInitials(String fullName) {
      return fullName.substring(0,1).toUpperCase();
   }
}

Thank you for your help and suggestions!

Upvotes: 1

Views: 12603

Answers (3)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79035

  1. In order to get the first name, you can get the substring from index 0 till the first whitespace (i.e. fullName.indexOf(' '))
  2. In order to get the initials, you can get the first char of the string + the first char after the last whitespace (i.e. fullName.lastIndexOf(' ')).

Demo:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        System.out.print("Enter full name: ");
        String fullName = reader.nextLine();

        System.out.print("Greetings, " + getFirstName(fullName) + ", your initials are " + getInitials(fullName));
    }

    public static String getFirstName(String fullName) {
        return fullName.substring(0, fullName.indexOf(' '));
    }

    public static String getInitials(String fullName) {
        int idxLastWhitespace = fullName.lastIndexOf(' ');
        return fullName.substring(0, 1) + fullName.substring(idxLastWhitespace + 1, idxLastWhitespace + 2);
    }
}

A sample run:

Enter full name: Arvind Kumar Avinash
Greetings, Arvind, your initials are AA

Upvotes: 3

somethingsmart
somethingsmart

Reputation: 43

What you want to do is break the fullname into a String array as such.

String[] names = fullName.split("\\s+"); //splits fullname at each space

Then you can use a loop to uppercase each part of the name

for (int i = 0; i < names.length; i++) {
    // do your toUpperCasing stuff here 
}

Upvotes: 2

Andreas
Andreas

Reputation: 344

You can split your string at all blanks and use the first entry of the array as your first name using the method split of String. For the initials you just use all entries of the array.

Upvotes: 2

Related Questions