【问题标题】:Java : Count duplication in first and last letters of String arrayJava:计算字符串数组的第一个和最后一个字母中的重复
【发布时间】:2018-10-07 20:57:21
【问题描述】:

我正在尝试计算字符串数组的第一个和最后一个字母中的重复。我有 2 个 int 数组,一个用于第一个字母,另一个用于最后一个字母。我想我必须以某种方式将它们都加入到 int [] 计数中,这样我才能传递给 displayCount。我如何加入他们?我知道我必须在 for 循环中添加一些东西,但我不确定要添加什么。现在它很重要并给了我错误的答案。请帮忙。谢谢。

public static int[] countChar(String[] str){
int[] begin= new int[26];
int[] end= new int[26];
for(int i=0;i<str.length;i++){
int x = str[0].charAt(0)-'a';
int y = str[0].charAt(str[0].length()-1)-'a';
begin[x]++;
end[y]++;
}
return begin; // I can return only one 
//value in a method how do I join begin and end together?
}
public static void displayCounts(int[] counts) {
    for (int i = 0; i < counts.length; i++) {
      System.out.println(counts[i] + " " + (char)(i + 'a'));
    }
}

public static void main(String[] args) {
   String[] str = {"julie","eleven","eve"};

    // Count the occurrences of each letter
    int[] counts = countChar(str);

    // Display counts
    System.out.println();
    System.out.println("The occurrences of each letter are:");
    displayCounts(counts);
  }
}

这就是它给我的答案。

The occurrences of each letter are:
0 a
0 b
0 c
0 d
0 e
0 f
0 g
0 h
0 i
3 j
0 k
0 l
0 m
0 n
0 o
0 p
0 q
0 r
0 s
0 t
0 u
0 v
0 w
0 x
0 y
0 z

【问题讨论】:

    标签: java arrays string char ascii


    【解决方案1】:

    创建包含两个数组的新类并使用并返回这个新类

    class Results {
    
      int begin [26];
      int end [26];
    
    }
    
    
    Results countChar(String[] str){
    
     Results results = new Results ();
     .
     .
     .
     results.begin[x]++;
     return results ;
    
    }
    

    编辑

    顺便说一下,我觉得你需要改成

    int x = str[i].charAt(0)-'a';
    int y = str[i].charAt(str[i].length()-1)-'a';
    

    因为你只看第一个字符串,否则

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-09
      • 1970-01-01
      • 2013-06-17
      • 2018-07-21
      • 1970-01-01
      • 2016-10-16
      • 1970-01-01
      相关资源
      最近更新 更多