【问题标题】:Java: How to fix "String index out of range: #"? [duplicate]Java:如何修复“字符串索引超出范围:#”? [复制]
【发布时间】:2019-08-17 03:01:03
【问题描述】:

我试图打乱一个字符串的两个随机字母,它们不是第一个字母,也不是最后两个。编译时出现“字符串索引超出范围”错误。我尝试了许多不同的解决方案,但似乎没有任何效果。

对于这个赋值,我们必须使用方法和 .charAt 命令。我尝试为两个随机字符创建变量,然后将它们添加回翻转的字符串中,但也无法使其正常工作。

public static String scramble(String input) {
    int range = input.length() - 3;
    int place = (int)(Math.random() * range);
    String newWord = "";
    newWord = input.substring(0, place);
    newWord = newWord + newWord.charAt(place) + 2;
    newWord = newWord + newWord.charAt(place) + 1;

    return newWord;

我期待一个字符串的输出,其中两个字符被打乱。例如,“Fantastic”将是“Fantsatic”或“Fnatastic”。

【问题讨论】:

  • 在调用 .chartAt 之前确保“place”值不大于字符串长度
  • 编译时为什么会报错?

标签: java string methods


【解决方案1】:

试试这样的:

public static String scramble(String input) {
    int range = input.length() - 3;
    int place = (int)(Math.random() * range);
    String newWord = input.substring(0, place);
    newWord = newWord + input.charAt(place + 1);
    newWord = newWord + input.charAt(place);
    // if you need the whole input, just 2 characters exchanged, uncomment this next line
    // newWord = newWord + input.substring(place + 2, range);
    return newWord;
}

【讨论】:

    【解决方案2】:

    你可以试试

      public static String scramble(String input) {
        if(input.length() >3){
            int range = input.length() - 3;
            int place  = 1+   new Random().nextInt(range) ;
            input=input.substring(0, place) +input.charAt(place  + 1)+input.charAt(place) +input.substring( place+2);
    
        }
        return input;
    }
    

    输入:太棒了 输出:Fanatstic,Fatnastic,Fanatstic

    【讨论】:

      【解决方案3】:

      当您创建 newWord = input.substring(0, place) 时,它正好有 place 字符。你不能向它请求charAt(place),最后一个字符在place-1

      如果要交换字符,请将输入转换为 char[] 并生成随机索引以进行交换。

      String input = "Fantastic";
      
      // random constraints
      int min = 1;
      int max = input.length() - 3;
      
      // random two characters to swap
      int from = min + (int) (Math.random() * max);
      int to;
      do {
          to = min + (int) (Math.random() * max);
      } while (to == from); // to and from are different
      
      // swap to and from in chars
      char[] chars = input.toCharArray();
      char tmp = chars[from];
      chars[from] = chars[to];
      chars[to] = tmp;
      String result = new String(chars);
      
      System.out.println(result); // Ftntasaic
      

      【讨论】:

        【解决方案4】:

        你会的:

        newWord = input.substring(0, place);
        

        所以newWord 中的索引从0 变为place-1
        然后你做:

        newWord.charAt(place);
        

        但是您的字符串中不存在此索引。是Out of Bound

        the doc

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多