对象数组那里错了
package javaapplication1;class gouwu{
String name;
int danjia;
int shuliang;
int sum;
public void fff(int danjia,int shuliang, String name){
this.danjia=danjia;this.shuliang=shuliang;this.name=name;
}
public void gouwu(gouwu a[]){
for (int i=0;i<a.length;i++)
{
sum=sum+a[i].danjia*a[i].shuliang;
}
System.out.print(sum);
}
}
public class Main {
public static void main(String[] args) {
gouwu []a=new gouwu[3];
a[0].fff(1, 1, "a");
a[1].fff(2,2,"b");
a[2].fff(3, 3, "c");
gouwu b=new gouwu();
b.gouwu(a);
}
}
a[0].fff(1, 1, "a");
a[1].fff(2,2,"b");
说是这里有问题
搜索更多相关的解决方案:
对象
----------------解决方案--------------------------------------------------------
你没有创建对象,空指针异常
程序代码:
package javaapplication1;
class Gouwu { //类名首字母要大写
String name;
int danjia;
int shuliang;
int sum;
public void fff(int danjia, int shuliang, String name) {
this.danjia = danjia;
this.shuliang = shuliang;
this.name = name;
}
public void gouwu(Gouwu a[]) {
for (int i = 0; i < a.length; i++) {
sum = sum + a[i].danjia * a[i].shuliang;
}
System.out.print(sum);
}
}
public class Main {
public static void main(String[] args) {
Gouwu[] a = new Gouwu[3];
a[0] = new Gouwu();//创建对象
a[1] = new Gouwu();//创建对象
a[2] = new Gouwu();//创建对象
a[0].fff(1, 1, "a");
a[1].fff(2, 2, "b");
a[2].fff(3, 3, "c");
Gouwu b = new Gouwu();
b.gouwu(a);
}
}
class Gouwu { //类名首字母要大写
String name;
int danjia;
int shuliang;
int sum;
public void fff(int danjia, int shuliang, String name) {
this.danjia = danjia;
this.shuliang = shuliang;
this.name = name;
}
public void gouwu(Gouwu a[]) {
for (int i = 0; i < a.length; i++) {
sum = sum + a[i].danjia * a[i].shuliang;
}
System.out.print(sum);
}
}
public class Main {
public static void main(String[] args) {
Gouwu[] a = new Gouwu[3];
a[0] = new Gouwu();//创建对象
a[1] = new Gouwu();//创建对象
a[2] = new Gouwu();//创建对象
a[0].fff(1, 1, "a");
a[1].fff(2, 2, "b");
a[2].fff(3, 3, "c");
Gouwu b = new Gouwu();
b.gouwu(a);
}
}
----------------解决方案--------------------------------------------------------
gouwu []a=new gouwu[3];
数组元素为空。相当于创建String[] s=new String[3]而没有赋值,所为应该这样写:
gouwu [] a = new gouwu [3];
a[0]=new gouwu();
a[1]=new gouwu();
a[2]=new gouwu();
a[0].fff(1, 1, "a");
a[1].fff(2, 2, "b");
a[2].fff(3, 3, "c");
这样每个数组元素中就存放了一个对象,
----------------解决方案--------------------------------------------------------
谢谢
----------------解决方案--------------------------------------------------------
你的代码有很不规范,建议你参看本版置顶的《JAVA代码规范》
类名首字母要大写
构造函数名与类名一样首字母要大写
其他方法名首字母小写
----------------解决方案--------------------------------------------------------
学习,学习
----------------解决方案--------------------------------------------------------
回复 2楼 lampeter123
变量名头单不用大写,以后的要大写 ----------------解决方案--------------------------------------------------------