【问题标题】:Am new to java. trying to find First recurring character in a string.I don't know where it was wrong.below is my code我是java新手。试图在字符串中找到第一个重复出现的字符。我不知道哪里错了。下面是我的代码
【发布时间】:2017-11-07 13:23:22
【问题描述】:
public static void main(String[] args) throws IOException {
    InputStreamReader in=new InputStreamReader(System.in);
    BufferedReader br=new BufferedReader(in);
    System.out.println("Enter the string");
    String s=br.readLine();
    char[] ch=s.toCharArray();
    findtherepeatechar(ch);
}
private static char findtherepeatechar(char[] ch) {
    int i;
    int count[]= {0};
    for( i=0;i<ch.length;i++) {
        count[ch[i]]++;
    }
    for(i=0;i<ch.length;i++)
        if(count[ch[i]]>1) {
            return ch[i];
        }else {
            return '\0';
        }
    return 0;
}

}

输入字符串

ABCD

线程“主”java.lang.ArrayIndexOutOfBoundsException 中的异常: 65 在 strs.findtherepeatechar(strs.java:18) 在 strs.main(strs.java:12)

提前致谢

【问题讨论】:

  • 调试器会很快告诉你。那个计数数组显然是不对的。您似乎想要对每个字母进行计数,但这不是您在方法开始时分配的。
  • 另外看看Java naming conventionIndexOutOfBoundsException表示你不在你的数组里了。
  • 将 int count = {0} 更改为 int count[]= new int[1000];

标签: java indexoutofboundsexception


【解决方案1】:

一些小的更新(数组是最重要的)就足够了:

public static void main(String[] args) throws IOException {
    InputStreamReader in = new InputStreamReader(System.in);
    BufferedReader br = new BufferedReader(in);
    System.out.println("Enter the string");
    String s = br.readLine();
    char[] ch = s.toCharArray();
    System.out.println(findtherepeatechar(ch));
}

private static char findtherepeatechar(char[] ch) {
    int i;
    int count[] = new int[256];
    for (i = 0; i < ch.length; i++) {
        count[ch[i]]++;
        if (count[ch[i]] > 1) {
            return ch[i];
        }
    }
    return 0;
}

由于 ch[i] 值的范围是 0 到 255(嗯...不是 100% 正确),您需要一个长度为 256 的数组。您还需要在 main 的末尾添加 System.out.println方法。

【讨论】:

    【解决方案2】:

    为什么不使用MapSet

    private static void findTheRepeatedChar(char[] characters) {
        /*
         * logic: char are inserted as keys and their count as values. If map
         * contains the char already then increase the value by 1
         */
        Map<Character, Integer> map = new HashMap<Character, Integer>();
        for (Character character : characters) {
            if (map.containsKey(character)) {
                map.put(character, map.get(character) + 1);
            } else {
                map.put(character, 1);
            }
        }
        // Obtaining set of keys
        Set<Character> keys = map.keySet();
        /*
         * Display count of chars if it is greater than 1. All duplicate chars
         * would be having value greater than 1.
         */
        for (Character ch : keys) {
            if (map.get(ch) > 1) {
                System.out.println("Char " + ch + " " + map.get(ch));
            }
        }
    }
    

    我对代码进行了注释,让你理解它的逻辑。

    【讨论】:

      【解决方案3】:

      你可以试试这个。

      public static void main(String[] args) throws IOException {
          BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
          ArrayList<Character> chars = new ArrayList<>();
          String line = reader.readLine();
      
          if(line!=null) {
              //add every character into the array
              for (int i = 0; i < line.length(); i++) {
                  char x = line.charAt(i);
                  chars.add(x);
              }
      
              //check if some character is duplicate
              firstloop:
              for (int i = 0; i < line.length(); i++) {
                  char c = line.charAt(i);
                  for (int j = i+1; j < chars.size(); j++) {
                      Character a = chars.get(j);
                      if (a == c) {
                          //If character is duplicate
                          //System.out.println("Character: "+ a + " is duplicate.");
                          //TODO
                          break firstloop;
                      }
                  }
              }
      
      
          }
      
      }
      

      【讨论】:

        【解决方案4】:

        逻辑很简单。如果我们没有看到字符串中的字符,我们将它放在哈希表中,否则我们将打印它

         public static void main(String[] args) {
            String[] dummyList= {"ABCA", "BCABA", "ABC", "DBCABA"};
            for (String s : dummyList) {
                System.out.println("Result=" + findIfStringHasRecurringChar(s));
            }
         }
        
         private static Character findIfStringHasRecurringChar(String s) {
            Hashtable<Character, Integer> letters = new Hashtable<>();
            for (char c : s.toCharArray()) {
                if (!letters.containsKey(c)) 
                    letters.put(c, 1);
                else 
                    return c;      
            }
            return null;
         }
        

        输出是:

        Result=A
        Result=B
        Result=null
        Result=B
        

        【讨论】:

          【解决方案5】:

          你的代码有几个问题,

          1. 首先,不影响编译器,但影响我们的眼睛和代码的易读性,看看Java Naming Convention

          为了便于理解,使用驼峰式大小写,findTheRepeatedChar 而不是 findtherepeatedchar

          1. 还可以查看Java arrays

          int[] count = {0} 将定义一个固定大小为 1 的数组,因此当您尝试访问更大的索引时,它会抛出异常。

          因此,您最好定义一个更大的数组 (int bigArray = new int[bigNumber]) 或使用其他结构,如 ListsMaps,具体取决于您的应用程序。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2023-03-28
            • 2022-06-13
            • 2021-01-12
            • 2018-04-25
            • 2011-01-23
            • 1970-01-01
            • 2018-06-12
            • 2017-04-28
            相关资源
            最近更新 更多