Java - 子串逻辑

标签 java

我已经尝试不同的事情有一段时间了,但我不明白为什么我的逻辑是错误的。这没有道理。

我正在尝试根据以下伪代码编写一个程序。

<小时/>

将以下用于随机排列字符串中的字符的伪代码翻译成 Java 程序。

  1. 读一个单词。
  2. 重复循环 word.length() 次
  3. 在单词中随机选择一个位置 i,但不是最后一个位置。
  4. 在单词中随机选择一个位置 j > i。
  5. 交换位置 j 和 i 处的字母。
  6. 打印单词。
  7. 然后将字符串替换为:first + word.charAt(j) + middle + word.charAt(i) + last

这是我到目前为止所拥有的:

package assignment4;

import java.util.Scanner;

public class P4Point7 {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        System.out.print("Please enter a word: ");
        String word = in.next();
        in.close();

        int wordLength = word.length(); // Gets the word.Length
        int x = 1; // Primes the loop

        while (x <= wordLength) {
            int i = (int) ((Math.random() * wordLength) - 1); // Gets a random letter i that is not the last letter
            int j = (int) (Math.random() * (wordLength - i)) + i; // Gets a random letter j after i 
            String first = word.substring(0, i); // Gets first part of word
            String middle = word.substring(i + 1, j); // Gets middle part of word
            String last = word.substring(j + 1, wordLength); // Gets last part of word
            x++; // Increments the loop
            String status = first + word.charAt(j) + middle + word.charAt(i) + last; // Swaps i and j in the word
            System.out.println(status);
        }   
    }
}

我遇到的问题是

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(Unknown Source)
at assignment4.P4Point7.main(P4Point7.java:21)

我正在用“Waffle”一词测试该程序。

最佳答案

  i = (int) ((Math.random() * wordLength) - 1); 
  j = (int) (Math.random() * (wordLength - i)) + i; //  

在这两行中,有 case (int) (Math.random() * (wordLength - i)) 将导致 0i == j。如果是这样,则以下代码行:

String middle = word.substring(i+1, j); 
          // if i==j, then  i+1 > j which will result in index exception.
  1. 用调试器一步步彻底调试你的代码,找出BUG。
  2. 使用Random类有一个很好的函数 random.nextInt(n) 来返回 0(含)和指定值(不含)之间的随机整数。

关于Java - 子串逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19351223/

相关文章:

java - 使用正则表达式捕获字符串之间的日期的解决方案是什么?

java - 将数据从 Android Activity 发送到 Web 表单

java - 如何使用 Angular 2 在 Spring 引导中导出 excel 文件?

java - 创建无限数量的项目

java - 程序世界生成

java - NumberFormat 与 Joda 货币

java - 是否可以将 Servlet 配置为不自动关闭响应的 OutputStream?

java - 谷歌应用引擎: When is auto id available?

java - 无法将 CoreNLP Shift-Reduce 模型加载到 CoreNLP jar 中

java - 面对 java.lang.NoSuchMethodError : HttpServletRequest. getParts()Ljava/util/Collection