[英]Iterate through an Arraylist of Chars
我正在嘗試制作一個輸入字符串並返回拼寫錯誤的方法(通過刪除一些隨機字符)。 由於某種原因,我的迭代器在id.remove()的行上給了我一個空錯誤。 有任何想法嗎?
public static String getMissSpelledWord(String str) {
Random random = new Random();
char[] character = str.toCharArray();
String misspelled = new String();
ArrayList<Character> chars = new ArrayList<Character>();
for (int i = 0; i < character.length; i++) {
chars.add(character[i]);
}
for (Iterator < Character > id = chars.iterator(); id.hasNext();) {
int remove = random.nextInt(3);
if(remove == 0) {
id.remove();
}
}
for(char c : chars) {
misspelled += c;
}
return misspelled;
}
您必須先調用Iterator.remove()
才能調用Iterator.next()
(因為鏈接的Javadoc注釋從此底層集合中移除了此Iterator返回的最后一個元素 )。 只需在循環體中添加id.next()
,例如
for (Iterator<Character> id = chars.iterator(); id.hasNext();) {
char ch = id.next(); // <-- add this.
int remove = random.nextInt(3);
if (remove == 0) {
id.remove();
}
}
沒有ArrayList的情況下,通過簡單地向前移動char數組中的隨機數來執行此操作會更簡單。
public static String getMisspelledWord(String str) {
Random random = new Random();
char[] character = str.toCharArray();
String misspelled = "";
for (int i = 0; i < character.length; i += random.nextInt(3) / 2 + 1) {
misspelled += character[i];
}
return misspelled;
}
Iterator.remove引發IllegalStateException-如果尚未調用下一個方法,或者在上次調用下一個方法之后已經調用了remove方法。 和UnsupportedOperationException-如果此迭代器不支持remove操作。
在您的情況下,您不應得到null錯誤,應該拋出IllegalStateException
。
考慮您的用例,如果添加id.next();
在id.remove();
之前id.remove();
直到迭代器具有元素為止,循環將一直運行,並且將一直運行到字符為空時,使您的拼寫錯誤始終為空。
嘗試這個
public static String getMissSpelledWord(String string) {
char charArray[] = string.toCharArray();
Random random = new Random();
StringBuilder stringBuilder = new StringBuilder();
for (int index = 0; index < charArray.length; index++) {
if (random.nextInt(3) == 0) {
continue;
}
stringBuilder.append(charArray[index]);
}
return stringBuilder.toString();
}
經過測試,工作正常
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.