【问题标题】:I can't call an array from a class我不能从一个类中调用一个数组
【发布时间】:2014-12-31 14:55:54
【问题描述】:

我想要的是计算每个单词的字母。然后用数组列出它。我在一个名为 WordLengths 的类中编写了一个方法,当我尝试调用它时。我得到 [4, 4, 4, 4, 4, 4, 4, 4, 4, 4] 而不是 [4, 2, 6, 5] 你能帮忙吗?

public class quiz3 {

   public static void main(String[] args) {
       String s;
       s = "This is really easy.";
       System.out.print(Arrays.toString(WordLengths.getArrayList(s) + " "));//The line with the problem.
   }
}


public class WordLengths {   

    private String s;

    public WordLengths(String s) {
         this.s = s;
    }

    public static int[] getArrayList(String s) {
       int i, x, j;
       x = 0;
       char c;
       int[] list = new int[10];
       for (i = 0; i <= s.length() - 1; i++) {
           c = s.charAt(i);
           if (c == ' ' ) {
               for(j = 0; j <= list.length - 1; j++) {
                  if(list[j] == 0) {
                      list[j] = x;
                  }
               } 
               x = 0;
          } else if (i == s.length() - 1) {
              x++;
              for(j = 0; j <= list.length - 1; j++) {
                  if(list[j] == 0) {
                      list[j] = x;
                  }
              }
              x = 0;
          } else 
          x++;
      }
      return list;
  }
}

【问题讨论】:

  • WordLengths.getArrayList(s) + " " 是一个字符串,不能作为Arrays.toString 的参数
  • 在此处检查括号System.out.print(Arrays.toString(WordLengths.getArrayList(s) + " "));。它将是Arrays.toStrin(int[] + " ")

标签: java arrays class methods


【解决方案1】:

从参数中删除连接的字符串:

System.out.print(Arrays.toString(WordLengths.getArrayList(s)));

参数WordLengths.getArrayList(s) + " "是字符串类型。

【讨论】:

  • 是的,它解决了问题。谢谢。可以看看输出问题吗?
【解决方案2】:

WordLengths.getArrayList(s) + " " 是一个字符串。

删除+ " ",所以类型是WordLengths.getArrayList(s)之一,即int[]

【讨论】:

  • 可以看看输出问题吗?
【解决方案3】:

您知道,您可以将 String 转换为 Characters 数组,然后将该数组的 length 属性提取为字符数。我会试试的。

String str = "testString";
char[] charArray = str.toCharArray();
System.out.println("Word Length : " + charArray.length);

【讨论】:

  • 可以看看输出问题吗?
【解决方案4】:

解决您的输出问题。

  • 将字符串拆分成单词
  • 为长度创建一个数组
  • 存储每个单词的长度

    public static int[] getArrayList(String s) {
        String[] words = s.split("\\s");
        int[] list = new int[words.length];
        for (int wordIdx = 0; wordIdx < words.length; wordIdx++) {
            list[wordIdx] = words[wordIdx].length();
        }
        return list;
    }
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-25
    相关资源
    最近更新 更多