I am writing a short Java program that is supposed to take in a list of 5 integers and assign each to one of 6 members. I want to maximize the number of members who are receiving a value between their min
and max
values.
Anyways, for some reason that is unknown to me, my private member
class seems to be throwing a NullPointerException, but I am at a complete loss as to why. Any suggestions would be appreciated.
import java.util.*;
public class assign {
private class member {
private String name;
private int min;
private int max;
public member(String name, int min, int max) {
this.name = name;
this.min = min;
this.max = max;
}
}
public member[] members = {
new member("Phil", 1, 20),
new member("Molly", 1, 20),
new member("Connor", 21, 40),
new member("Sam", 21, 40),
new member("Dan", 41, 60),
new member("Theresa", 41, 60)
};
public void main(String[] args) {
System.out.println("test");
String s = StdIn.readLine();
String[] temp = s.split(" ");
ArrayList<Integer> nums = new ArrayList<Integer>(5);
for (int i = 0; i < 5; i++) {
nums.add(Integer.parseInt(temp[i]));
}
ArrayList<member> mems = new ArrayList<member>(Arrays.asList(members));
for (int n : nums) {
for (member m : mems) {
if (n > m.min && n < m.max) {
System.out.println(m.name + " : " + n);
nums.remove(n);
mems.remove(m);
}
}
}
for (int n : nums) {
member m = mems.remove(0);
System.out.println(m.name + " : " + n);
}
}
}
From OP's comment:
java.lang.NullPointerException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
I'm betting that your error is that your current main method is not static:
// this should be a static method
public void main(String[] args) {
// ...
}
Solution: make the main method static as it should be.
public static void main(String[] args) {
// ...
}
Once you fix this, you'll see other errors, mainly that you're trying to access non-static things in a static way. To fix this, you'll want to give your assign class (please rename this Assign so that it starts with an upper case letter) public methods to call, and then have your main method create an Assign instance and call these methods.
For instance here:
ArrayList<member> mems = new ArrayList<member>(Arrays.asList(members));
You're trying to use the non-static members array in a static context. You will want to only handle it inside your Assign class, inside of its public methods. Either that or make members
static.