String.replace()中的java.lang.NullPointerException

时间:2014-03-12 19:56:40

标签: java string

我觉得我应该知道代码的用途。我有这个问题,我需要编写两个函数,一个是find(),如果它找到给定字符串中的子字符串的索引,则返回一个布尔值。该函数应该“将索引值保存在索引数组中”。另一种方法是replace()用新单词替换所有搜索到的单词,然后输出新字符串。需要输出匹配单词的索引号。

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;
    } 
}

现在的问题是,我在注释行中发现了nullpointer异常。你能告诉我问题出在哪里吗?我搜索错误无济于事。

5 个答案:

答案 0 :(得分:2)

你的替换为null;你指派两次。

答案 1 :(得分:1)

你犯了一个小错误,当你要求替换字符串时,你将输入存储在字符串find中,而不是replace中。 替换为:

System.out.print("Enter the string to replace with: ");
replace = scanner.nextLine();

答案 2 :(得分:0)

您的replace变量为null。你需要解决这个问题

答案 3 :(得分:0)

改变这个:

System.out.print("Enter the string to find: ");
find = scanner.nextLine();
System.out.print("Enter the string to replace with: ");
find = scanner.nextLine();

对此:

System.out.print("Enter the string to find: ");
find = scanner.nextLine();
System.out.print("Enter the string to replace with: ");
replace = scanner.nextLine();

答案 4 :(得分:0)

因为你的replace变量为null,你将作为参数传递。

根据Java文档

" passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown"