【发布时间】:2015-07-31 19:13:24
【问题描述】:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
public class MachinePedagogy {
public static void main(String[] args) throws IOException {
changeVowel("dictionary.txt");
}
private static void changeVowel(String path) throws IOException {
char ch;
BufferedWriter bWriter = new BufferedWriter(new FileWriter(new File("changevowel.txt")));
String aeiou = "aeiou";
char[] vowels = aeiou.toCharArray();
BufferedReader bReader = new BufferedReader(new FileReader(new File(path)));
for(String temp = bReader.readLine(); temp != null; temp = bReader.readLine()){
int counter = 0;
char[] characters = temp.toCharArray();
for(int i = 0; i < temp.length(); i++){
ch = temp.charAt(i);
if(
ch == 'a' ||
ch == 'e' ||
ch == 'i' ||
ch == 'o' ||
ch == 'u'){
counter++;
}
}
Random rand = new Random();
int vIndex[] = new int[counter];
int index = 0;
for (int j = 0; j <temp.length(); j++){
ch = temp.charAt(j);
if(
ch == 'a' ||
ch == 'e' ||
ch == 'i' ||
ch == 'o' ||
ch == 'u'){
vIndex[index] = j;
index++;
}
}
int random2 = (rand.nextInt(vIndex.length));
int random1 = (rand.nextInt(vowels.length));
characters[vIndex[random2]] = vowels[random1];
temp = String.valueOf(characters);
bWriter.write(temp + "\n");
}
bReader.close();
bWriter.close();
}
}
为什么我的 bound 有时在这些数组上是负数?
Exception in thread "main" java.lang.IllegalArgumentException: bound must be positive
at java.util.Random.nextInt(Unknown Source)
at MachinePedagogy.changeVowel(MachinePedagogy.java:56)
at MachinePedagogy.main(MachinePedagogy.java:14)
第 56 行:
characters[vIndex[random2]] = vowels[random1];
第 14 行:
changeVowel("dictionary.txt");
我想编辑字符串中的随机元音并将其更改为另一个随机元音,最好与以前不同。 Dictionary.txt 只是一本斯坦福词典,如果您需要它来编译代码。
我发现的许多替换元音的例子都遵循这个逻辑。
temp.replaceAll( "[aeiou]", "?" );
我不想替换所有元音,只想替换一个随机索引的元音。我认为这可能与 nextInt() 有关,但是当我阅读文档Random#nextInt(int) 时,我很困惑为什么会这样。我从其他 StackOverflow 问题中了解到,这是为数组生成随机索引的有效方法。
我写了一个拼写检查器,想测试它的准确性,因为经常犯的错误是改变单词的单个元音。我计划稍后通过对 dictionary.txt 运行 changevowel.txt 并从 changevowel.txt 中删除正确的单词来从我创建的大列表中删除正确的单词,但这对于手头的直接问题并不重要。
【问题讨论】:
-
嗯。问题是什么?
-
为什么我的绑定有时在这些数组上是负数?
-
请将其添加到 OP。另外,您如何确定界限是否为负?通过调试器?还是您只是看到异常?无论哪种方式,在代码中提供一个专门识别问题的位置
-
我很抱歉,Ben,我还是新来的,我正在努力正确有序地做所有事情,因为我看到其他人似乎提出了很好的问题。运行后,我在 Eclipse 的控制台中看到了异常。
-
不用担心一切顺利。这需要时间。我们来看看 StackTrace
标签: java arrays random indexoutofboundsexception illegalargumentexception