Convert array element to a string and print first character?

sethFrias :

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));
    }
}
GBlodgett :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=98250&siteId=1