【问题标题】:How to create an array list of strings using the .split() function?如何使用 .split() 函数创建字符串数组列表?
【发布时间】:2016-11-06 18:11:30
【问题描述】:

我正在尝试创建一个必须遵守以下内容的程序:

  1. 创建一个名为WordGroup的类;
  2. 有一个名为words的实例变量。
  3. 有一个接受字符串的构造函数。这将被转换为小写并存储在单词中。使用 String API 中的方法将字符串变为小写。
  4. 有一个名为getWordArray() 的方法,它返回一个String[]。使用 String 类split() 方法分隔“ ”上的单词。
  5. 创建两个 WordGroups 一个初始化为“你可以在一个小时的游戏中比在一年的对话中发现更多关于一个人的信息”,另一个初始化为“当你玩的时候,你工作的时候玩得很努力,根本不玩”//这些分别是柏拉图和罗斯福的引用,去掉了标点符号
  6. 使用getWordArray() 创建两个字符串数组。
  7. 编写两个 for 循环以遍历两个数组并打印出每个单词。

我目前停留在数字 6 上。我在 main 方法中创建了两个 WordGroup,但我不确定如何将它们分配给 getWordArray() 方法,以便它们创建一串数组。代码如下:

WordGroup 类

public class WordGroup {

    String word;

    //Creates constructor which stores a string value in variable "word" and converts this into lower case using the lower case method.
    public WordGroup(String aString) {
        this.word = aString.toLowerCase();
    }
    public String getWordArray; {

        word =("");
        String WordArray[] = word.split("-");

    }
}

主类

public class Main{

    public static void main (String[] args) {

        WordGroup firstWordGroup = new WordGroup.word("You-can-discover-more-about-a-person-in-an-hour-of-plau-tban-in-a-year-of-conversation");
        WordGroup secondWordGroup = new WordGroup ("When-you-play-play-hard-when-you-work-dont-play-at-all");

    }   
}

为了清楚起见,我想创建两个数组列表,它们使用.split() 函数使用getWordArray() 方法创建一个字符串数组,然后打印出数组列表。任何帮助将不胜感激,谢谢。

【问题讨论】:

标签: java arrays string


【解决方案1】:

您的代码无法编译。 getWordArray的正确版本如下:

public String[] getWordArray() {
    String[] wordArray = word.split("-");
    return wordArray;
}

如果您不从方法返回分配的变量,Main 类将永远不会知道它。相应的主类是:

public class Main{
    public static void main (String[] args) {
        WordGroup firstWordGroup = new WordGroup.word("You-can-discover-more-about-a-person-in-an-hour-of-plau-tban-in-a-year-of-conversation");
        WordGroup secondWordGroup = new WordGroup ("When-you-play-play-hard-when-you-work-dont-play-at-all");

        String[] firstWordArray =  firstWordGroup.getWordArray();
        for( String word : firstWordArray) { 
            System.out.println(word);
        }
        //second loop is very similar.
    }   
}

【讨论】:

    【解决方案2】:

    您的getWordArray 没有按照#4 告诉您的那样做。您需要在 String 后面加上方括号 [] 来告诉它返回一个字符串数组。你也没有return语句。

    public String[] getWordArray() {
        return word.split("-");
    }
    

    在#6 中如何使用它来创建字符串数组是从你创建的两个变量中调用你的方法。

    String[] wordArray1 = firstWordGroup.getWordArray();
    String[] wordArray2 = secondWordGroup.getWordArray();
    

    【讨论】:

      猜你喜欢
      • 2011-08-20
      • 2013-07-14
      • 1970-01-01
      • 1970-01-01
      • 2019-07-07
      • 1970-01-01
      • 2019-05-03
      • 1970-01-01
      • 2022-01-24
      相关资源
      最近更新 更多