Trying to create a method findNewLineWithChar()
which returns a String and accepts a Scanner scn
and a char c
. It returns the line of the scanner which contains c
.
I've tried using a string to store the value of currentLine, but it seemed to convolute my code and not provide any answers anyways. I would love to use a String[], but I get a NullPointerException. What am I exactly doing wrong?
public static String findLineWithChar(Scanner scn, char c) {
/*
* findLineWithChar returns line in scanner if line has char c
* @param scanner
* @param c
*/
String result = "";
String[] stringArray = new String[10]; //accepts max 10 lines
int counter = 0; //populate string array from scn
while(scn.hasNextLine()) {
stringArray[counter] = scn.nextLine();
counter++;
}
//iterate through each element in string array
for (int i = 0; i < 10; i++) {
if (stringArray[i].contains(c + "")) {
result = stringArray[i];
System.out.println(stringArray[i]);
break;
} else {
result = "";
}
}
return result;
}
It works if I feed it a true statement,
findLineWithChar(new Scanner("Look here!\nLook there!\nExtra extra!"), 'x')
returns Extra extra!
, but findLineWithChar(new Scanner("Look here!\nLook there!\nExtra extra!"), 'q') returns a NullPointerException. How do I deal with this?