IM上将对象添加到7个对象的数组有点混乱。
我有一个循环,我想用3个参数添加项目对象。 我已经使用set和get这一点。 在的结束for循环中,Id喜欢。新增项对象到阵列列表。 当我尝试这样做,我得到一个错误:
例外在线程 “主” 显示java.lang.NullPointerException在item.add(item.java:88)在homework3main.main(homework3main.java:38)
有上线88项级和38主没有错误标志,所以我不知道如何改正。
public class item {
public static int x = 0;
public static String setName;
public static double setPrice;
public static int setPrioirty;
public int priority=-1;
public static double price;
public static String name;
private static item[] list;
item(){
this(-1,0, null);
priority=-1;
price=0;
name="No Name yet.";
}// default constructor.
public item(int i, double j, String k) {
setitem(i,j,k);//constructor with 3 arguments.
}
public void setitem (int i, double j, String k){// setting item with 3 attributes.
setPriority(i);
setPrice(j);
setName(k);
}
public void setName(String k) {//setting individual attributes in item.
// TODO Auto-generated method stub //page 378
name=k;
priority=-1;
price=0;
}
public void setPrice(double j) {//setting individual attributes in item.
// TODO Auto-generated method stub
if (j<0&&j>100){
System.out.println("Error: price is too low or high");
}
else
price=j;
}
public void setPriority(int i) {//setting individual attributes in item.
// TODO Auto-generated method stub
priority =((i>=0&&i<7)?i:0);
}
public double getPrice(){
return price;
}
public String getName(){
return name;
}
public double getPriority(){
return priority;
}
// eclipse made me create this method when I wanted to "add an itemObject to the list"
public static void add(item itemObject) {
System.out.println("Enter an item"+x);
if (x<7)
{
list[x]=itemObject;
System.out.println("Item added at index " + x);
x++;
}
}
}
- - - - - - - - - - - - - - - - -主要
public class homework3main extends item {
public static void main(String[] args) {
item list[]=new item [7]; // array object
Scanner keyboard= new Scanner(System.in);
for(int x=0; x<list.length;x++){
item itemObject=new item (setPrioirty,setPrice,setName);
//creating new object with 3 variables, name, price, priority
//list[x]=new item();// is this right?
System.out.println("Enter an item you want to add to your list");
list[x].setName=keyboard.next();
System.out.println("Enter a price");
Scanner pricedouble= new Scanner(System.in);
list[x].setPrice=pricedouble.nextDouble();
System.out.println("Enter the priority of the item");
Scanner priorityint= new Scanner(System.in);
list[x].setPrioirty=priorityint.nextInt();
//item itemObject=new item (setPrioirty,setPrice,setName);
list[x].add(itemObject);
}