Home > database >  How do I put a remove a leading space when printing something in java?
How do I put a remove a leading space when printing something in java?

Time:10-20

How do I put a remove a leading space when printing something in java?

import java.util.Scanner;
import java.io.IOException;
public class InitialsProject {
    public static void main(String args[]) throws IOException {   
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter your name: ");
        String name = scan.nextLine();
        char firstInitial = name.charAt(0);
        int index = name.indexOf(" ");
        System.out.println(firstInitial   name.substring(index  ,index 1));
   }
}

Sample input: John Doe

Output: J D

CodePudding user response:

So your question is a little vague, but I assume your issue is around "why does it print "J D" and not "JD""

The simple answer is index is post operation, that is, the value of index is first used (by substring), then it's updated. You could fix it by using a pre operation, ie index, but I would suggest that using index 1 (and index 2) is more readable and less error prone.

But...there are a number of ways you might perform this operation

For example, you could simply use String#split

String text = "John Doe";
String[] parts = text.split(" ");
if (parts.length == 1 && !parts[0].isEmpty()) {
    System.out.println(parts[0].charAt(0));
} else if (parts.length == 2) {
    if (!parts[0].isEmpty() && !parts[1].isEmpty()) {
        System.out.println(parts[0].charAt(0)   " "   parts[1].charAt(0));
    } else if (!parts[0].isEmpty()) {
        System.out.println(parts[1].charAt(0));
    } else if (!parts[1].isEmpty()) {
        System.out.println("..."   parts[1].charAt(0));
    } else {
        System.out.println(text   " is an invalid input");
    }
} else {
    System.out.println(text   " is an invalid input");
}

nb: I'm been a little defensive, can't help it

Or you could simply use charAt directly...

int index = text.indexOf(" ");
if (index >= 0) {
    if (index   1 < text.length()) {
        System.out.println(text.charAt(0)   " "   text.charAt(index   1));
    } else {
        System.out.println(text.charAt(0));
    }
} else {
    // Handle all the other possible conditions
}

Both the examples will print J D

CodePudding user response:

Simply using charAt would do the trick,

System.out.println(firstInitial   name.charAt(index 1));
  • Related