returning string containing char c in scanner

我是研究僧i 提交于 2021-02-17 03:16:24

问题


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?


回答1:


First, Javadoc comments go before the method (and start with /**). Second, you don't need an array here; just keep a count to make sure you don't consume more than ten lines (assuming that's necessary). Instead of setting a return variable and breaking the loop, I would return when a matching line is found. I would also prefer String.indexOf(int) to building one character String(s) for comparison. And, add a default return value for when nothing matches. Like,

/**
 * findLineWithChar returns line in scanner if line has char c
 * 
 * @param scanner
 * 
 * @param c
 */
public static String findLineWithChar(Scanner scn, char c) {
    int counter = 0;
    while (scn.hasNextLine() && counter < 10) {
        String line = scn.nextLine();
        if (line.indexOf(c) > -1) {
            return line;
        }
        counter++;
    }
    return "";
}



回答2:


You almost got it! Just change condition of your while loop.

from this:

while(scn.hasNextLine()) {

to this:

while(scn.hasNextLine() && counter < 10) {


来源:https://stackoverflow.com/questions/58001448/returning-string-containing-char-c-in-scanner

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!