老師布置了一個作業,大致如下.
在一篇文章中,例如:
Abc.Def.Ghk.Gml.Zkb.
需要用戶輸入一個字符.
然後輸出前後文.
如用戶輸入e, 則輸出前一個句子,自身句子,和後面的句子.即輸出
Abc.DEf.Ghk. (同時需要把用戶輸入的字符大寫)
如果前面或者後面沒有句子,則可以忽略.
老師說需要用至少一個靜態方法完成.
在此請教各位.
public static String foo(String text, String find) {
String lowertext=text.toLowerCase();
String arr[] = text.split("\\.");
String lowerArr[] = text.split("\\.");
String lowerfind = find.toLowerCase();
for (int i = 0; i < arr.length; i++) {
if (lowerArr[i].indexOf(lowerfind) != -1) {
if (i == 0)
return arr[0] + "." + arr[1] + ".";
else if (i > 0 && i < (arr.length) - 1)
return arr[i - 1] + "." + arr[i] + "." + arr[i + 1] + ".";
else if (i == (arr.length) - 1)
return arr[i - 1] + "." + arr[i] + ".";
}
if (arr[i].indexOf(find) != -1)
break;
}
return null;
}
public static void main(String[] args) {
String oriText = searchText();
Scanner input = new Scanner(System.in);
String cusInput = "";
while (cusInput.length() < 1) {
System.out.println("Please enter a word or a phrase and I will show its context");
cusInput = input.nextLine();
}
String lowerCaseInput = cusInput.toLowerCase();
String lowerCaseText = oriText.toLowerCase();
int a = lowerCaseText.indexOf(lowerCaseInput);
if (a == -1)
System.out.println("The text does not contain the specified phrase.");
else {
String result = foo(oriText, cusInput);
String upperCaseInput = lowerCaseInput.toUpperCase();
System.out.println("The phrase " + upperCaseInput + " appears in the following context:");
System.out.println("----------------------------------------------------------------");
System.out.println((result.replaceFirst(lowerCaseInput, upperCaseInput)));
}
}
}
以上是我的代碼,輸入某些結果的時候有時候能正確輸出,但有時候會顯示
context:Exception in thread "main"
java.lang.NullPointerException
at assignment4.main(assignment4.java:55)
這個錯誤代碼,請問該如何改正?
public static String foo(String s, String find)
{
String arr[] = s.split("\\.");
for (int i = 1; i < arr.length - 1; i++)
{
int pos =arr[i].indexOf(find);
if ( pos != -1)
arr[i] = arr[i].substring(0,pos) + (char)(arr[i].charAt(pos)+32)+arr[i].substring(pos+1);
if(pos == 0){
return arr[i] + "." + arr[i + 1];
}
return arr[i - 1] + "." + arr[i] + "." + arr[i + 1];
}
return "";
}