I feel like I should give an idea what the code is for. I have this problem where I need to write two functions, one is find() that returns a boolean value if it finds the index of a substring in a given string. The function is supposed to 'save the index values in the index array'. And another method, replace() that replaces all the searched words with the new word, and out put the new string. The index number of the matched words need to be output.
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;
}
}
Now the problem is, I am finding nullpointer exception at the commented lines. Can you tell me where the problem is? I searched the error to no avail.