简体   繁体   English

将数组元素转换为字符串并打印第一个字符?

[英]Convert array element to a string and print first character?

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 我没有成功使用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));
    }
}

You need to iterate over every String in the Array and then print the first char . 您需要迭代Array每个String ,然后打印第一个char You can do this using charAt() and a loop. 您可以使用charAt()和循环来完成此操作。

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

Or you can use Arrays.stream() : 或者你可以使用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. 您将要进入问题,因为nextInt()不使用换行符。 Add a blank nextLine() call after nextInt() nextInt()之后添加一个空白的nextLine()调用

  • You are looping until <= array.length which will cause an indexOutOfBounds error. 循环直到<= array.length ,这将导致indexOutOfBounds错误。 You need to only loop until less than array.length 您只需循环直到小于array.length

Just do another iteration over the "nameArray", and get the first character of each array element, and print it. 只需对“nameArray”进行另一次迭代,并获取每个数组元素的第一个字符,然后打印它。

For example, you can use for-each: 例如,您可以使用for-each:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM