我覺得我應該知道代碼的用途。我有這個問題,我需要編寫兩個函數,一個是find(),如果它找到給定字符串中子字符串的索引,它將返回一個布爾值。該函數應該「將索引值保存在索引數組中」。另一種方法是用替換()來替換所有搜索到的單詞,然後輸出新的字符串。需要輸出匹配詞的索引號。String.replace中的java.lang.NullPointerException()
import java.util.Scanner;
public class findAndReplace {
public static void main(String[] args) {
String text;
String find;
String replace = null;
String result;
int index[];
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the line: ");
text = scanner.nextLine();
System.out.print("Enter the string to find: ");
find = scanner.nextLine();
System.out.print("Enter the string to replace with: ");
find = scanner.nextLine();
find(text, find);
String result1 = replace(text, find, replace); //!!NUllPointerException
System.out.print(result1);
}
public static boolean find(String text, String find){ //method return a Boolean value if it finds the index of the word that we are trying to find. Saves the index value in the index array.
boolean b = false;
int index_int;
int index[] = null;
if (text.indexOf(find)>=0){
b = true;
int i = 0;
do{
index_int = text.indexOf(find);
index[i]=index_int;
i++;
text.replace(text.charAt(index_int), '0');
System.out.print(index_int);
} while (text.indexOf(find)>=0);
}
return b;
}
public static String replace(String text, String find, String replace){ //method replaces all search words with new word and prints.
String result;
result = text.replace(find, replace); //!!NUllPointerException
return result;
}
}
現在的問題是,我在註釋行發現空指針異常。你能告訴我問題在哪裏嗎?我搜索錯誤無濟於事。
這是什麼線應該做的'find'方法:'text.replace(text.charAt(index_int), '0');'? 'String'的'replace'方法替換你的字符串中的東西並返回結果字符串,但是你只是將結果扔掉。 – ajb
它應該改變字符串,以便在下一次迭代時使用給定的子字符串選擇的索引是不同的。這不是工作。 – mrahh
'main'中的'replace'是什麼:一個'String'或一個'Method'? –