gpt4 book ai didi

Java - 子串逻辑

转载 作者:行者123 更新时间:2023-11-30 04:12:11 24 4
gpt4 key购买 nike

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

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

<小时/>

将以下用于随机排列字符串中的字符的伪代码翻译成 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com