Answer to Question #298882 in Java | JSP | JSF for Setner

Question #298882

Write a program to take a String name as input then display the name's first and last words as it was and the middle will be only first letter using substring and indexOf.

Example:

Enter a String

Meser chen Rixou xang

Meser c.R. xang

Don't use array and split


1
Expert's answer
2022-02-21T13:35:25-0500
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a String");
        String line = in.nextLine();
        int start = 0;
        while (true) {
            int index = line.substring(start).indexOf(' ');
            if (index == -1) {
                System.out.print(line.substring(start));
                break;
            }
            if (start != 0) {
                System.out.print(line.substring(start, start + 1) + ". ");
            } else {
                System.out.print(line.substring(start, start + index + 1));
            }
            start += index + 1;
        }
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS