我在将对象添加到 7 个对象的数组时有点困惑。
我有一个 for 循环,我想添加一个带有 3 个参数的项目对象。我已经为此使用了 set 和 get 。在 for 循环结束时,id 喜欢将 item 对象添加到数组列表中。当我尝试这样做时,我收到一个错误:
在 homework3main.main(homework3main.java:38) 的 item.add(item.java:88) 的线程“main”java.lang.NullPointerException 中的异常
item class 的第 88 行和 main 的第 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);
}