Convert array element to a string and print first character?

Viewed 2291

I need to create an array of strings from user input and print the first letter of each element. I'm aware that I need to convert the array to a string somehow, but unsure how to accomplish this. I was unsuccessful with Arrays.toString

Following is my code:

import java.util.Scanner;
import java.util.Arrays;
class Main{
    public static void main(String[] args){
        Scanner inp = new Scanner(System.in);
        System.out.println("How many names would you like to enter in this array?: ");
        int numName = inp.nextInt();
        String nameArray[] = new String[numName];
        System.out.println("Enter the names: ");

    for(int i = 0; i <= nameArray.length; i++){
          nameArray[i] = inp.nextLine();
        }
        System.out.println(nameArray.charAt(0));
    }
}
3 Answers

You need to iterate over every String in the Array and then print the first char. You can do this using charAt() and a loop.

for(String str : nameArray) {
   System.out.println(str.charAt(0));
}

Or you can use Arrays.stream():

Arrays.stream(nameArray).forEach(e -> System.out.println(e.charAt(0)));

Also just a few problems with your code:

  • You are going to enter into this problem, because nextInt() does not consume the newline. Add a blank nextLine() call after nextInt()

  • You are looping until <= array.length which will cause an indexOutOfBounds error. You need to only loop until less than array.length

Just do another iteration over the "nameArray", and get the first character of each array element, and print it.

For example, you can use for-each:

for(String name : nameArray) {
  System.out.println(name.charAt(0));
}
Arrays.stream(nameArray).map(s -> s.charAt(0)).forEach(System.out::println);
Related