2014-03-12 458 views
-1

我覺得我應該知道代碼的用途。我有這個問題,我需要編寫兩個函數,一個是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; 
    } 
} 

現在的問題是,我在註釋行發現空指針異常。你能告訴我問題在哪裏嗎?我搜索錯誤無濟於事。

+0

這是什麼線應該做的'find'方法:'text.replace(text.charAt(index_int), '0');'? 'String'的'replace'方法替換你的字符串中的東西並返回結果字符串,但是你只是將結果扔掉。 – ajb

+0

它應該改變字符串,以便在下一次迭代時使用給定的子字符串選擇的索引是不同的。這不是工作。 – mrahh

+0

'main'中的'replace'是什麼:一個'String'或一個'Method'? –

回答

2

你的替換爲空;你分配了兩次。

0

您的替換變量爲空。你需要修復

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(); 
0

它,因爲你的替代變量爲空,您作爲參數傳遞。

按Java文檔

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

你犯了一個小錯誤,當你問替換字符串,您輸入存儲在字符串find,而不是在replace。 這種替換:

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