在扫描仪中返回包含char c的字符串 [英] returning string containing char c in scanner
问题描述
尝试创建方法findNewLineWithChar()
,该方法返回String并接受扫描程序scn
和字符c
.它返回包含c
的扫描仪行.
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
.
我尝试使用字符串来存储currentLine的值,但是它似乎使我的代码复杂,并且始终无法提供任何答案.我很想使用String [],但得到了NullPointerException.我到底在做什么错?
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;
}
如果我提供真实的陈述,它会起作用,
findLineWithChar(new Scanner("Look here!\nLook there!\nExtra extra!"), 'x')
返回Extra extra!
,但是findLineWithChar(new Scanner("Look here!\ nLook there!\ nExtra extra!"),'q')返回NullPointerException.我该如何处理?
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?
推荐答案
首先,Javadoc注释在方法之前(并以/**
开头).其次,这里不需要数组;只是保持计数以确保您消耗的行数不超过十行(假设这是必要的).当找到匹配的行时,我将返回而不是设置返回变量并中断循环.我也希望 String.indexOf(int)
构建一个字符String
进行比较.并且,为没有匹配项时添加默认的返回值.喜欢,
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 "";
}
这篇关于在扫描仪中返回包含char c的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!