class huoException extends Exception
{
String message;
public huoException(int n)
{
message= "已装载:"+n+"t,已超重";
}
}
class chuan
{
public int zhongliang;//重量
public int xianzhong;//限重
public void xz(int x)
{
xianzhong = x;
}
public void income(int z) throws huoException
{
if( z > xianzhong )
{
throw new huoException(z);
}
zhongliang = zhongliang + z;
System.out.println("现在重量:"+zhongliang+"t");
}
public int now()
{
return zhongliang;
}
}
public class zhuanghuo
{
public static void main(String args[])
{
chuan zh = new chuan();
chuan.xz(1000);
try{
chuan.income(100);
chuan.income(500);
chuan.income(600);
chuan.income(200);
}
catch(huoException e)
{
System.out.println("出现如下问题:\n"+e.message);
}
System.out.println(chuan.now());
}
}
运行结果:
zhuanghuo.java:40: 错误: 无法从静态上下文中引用非静态 方法 xz(int)
chuan.xz(1000);
^
zhuanghuo.java:42: 错误: 无法从静态上下文中引用非静态 方法 income(int)
chuan.income(100);
^
zhuanghuo.java:43: 错误: 无法从静态上下文中引用非静态 方法 income(int)
chuan.income(500);
^
zhuanghuo.java:44: 错误: 无法从静态上下文中引用非静态 方法 income(int)
chuan.income(600);
^
zhuanghuo.java:45: 错误: 无法从静态上下文中引用非静态 方法 income(int)
chuan.income(200);
^
zhuanghuo.java:51: 错误: 无法从静态上下文中引用非静态 方法 now()
System.out.println(chuan.now());
^
6 个错误
实在不知道哪里有问题
chuan.xz(1000);
try{
chuan.income(100);
chuan.income(500);
chuan.income(600);
chuan.income(200);
改为
zh.xz(1000);
try{
zh.income(100);
zh.income(500);
zh.income(600);
zh.income(200);
很明显,你定义类没有用它,反而使用类名,但是你应该知道类名虽然可以调用方法,前提那个方法必须是静态方法,所以你写的方法不是静态方法,不能使用类名调用,而是现创建类,使用引用调用方法也就是你的zh
chuan.xz(1000);
try{
chuan.income(100);
chuan.income(500);
chuan.income(600);
chuan.income(200);
将chuan改成zh,你都写chuan zh = new chuan();为啥不用zh调用里面的方法?
另外建议你别再往后学了,从新学习java前面的知识,尤其书写规范,因为你都学到异常了却现在都不知道java的书写规范,这样找工作,别人看你代码真的认为你啥也不会的,即便你会但是给别人的感觉就是什么也不会!
1.类名首字母大写,(尽量命名有意义不要使用拼音) 小写的话,如何区分对象?
2.变量一般不使用拼音,采用英文单词(有意义的)
重量:weight 限度:limit 当变量为两个单词第二个单词首字母大写
这只是建议,如果你认为这样就行,可以继续往后学习,言尽于此