In another method (ALGO_1) I search over elements of <background>
and check the value H_NAME equals a value entered in the main. When I attempt to run the code, I get a null pointer exception. Upon trying to print (with System.out.println
etc) the H_NAME value after each for loop in the snippet, I also get a null statement returned to me.
I am fairly certain that the c开发者_运维知识库ollection is simply not storing the data gathered up by the Scanner. But when I check the collection size with size()
, it is about the right size.
Main questions are:
- from the readBackground method is the data.add in the wrong place?
- is the snippet simply structured wrongly?
When I use System.out.println
to check the Background object values name, start time, increment, etc., they print out fine.
for (Hydro hd: hydros) {
System.out.println(hd.H_NAME);
for (Background back : backgs) {
System.out.println(back.H_NAME);
if (back.H_NAME.equals(hydroName)) { //get error here
public static Collection<Background> readBackground(String url) throws IOException {
URL u = new URL(url);
InputStream is = u.openStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader b = new BufferedReader(isr);
String line ="";
Vector<Background> data = new Vector<Background>();
while ((line = b.readLine())!= null) {
Scanner s = new Scanner(line);
String name = s.next();
double starttime = Double.parseDouble(s.next());
double increment = Double.parseDouble(s.next());
double sum = 0;
double p = 0;
double nterms = 0;
while ((s.hasNextDouble())) {
p = Double.parseDouble(s.next());
nterms++;
sum += p;
}
double pbmean = sum/nterms;
Background SAMP = new Background(name, starttime, increment, pbmean);
data.add(SAMP);
}
return data;
}
If you get a NullPointerException (NPE) when you call back.H_NAME.equals(xxx)
, it probably means either back
is null or back.H_NAME
is null.
You say that when you print back.H_NAME
, you get null, so that suggests that back.H_NAME
is actually null. You haven't shown us any code that describes the class Background
, so it's hard to give you any more help.
精彩评论