我在java中编写了一个非常简单的程序,用于使用static关键字.但我得到输出为0.我无法找到原因.我是java的初学者.任何人都可以建议一个解决方案,也请解释为什么遇到这样的问题...我的代码如下:
public class Cube{
static int length;
static int breadth;
static int height;
public static int volume(final int i, final int j, final int k){
return length * breadth * height;
}
public static void main(final String args[]){
System.out
.println("volume of the cube is : " + Cube.volume(10, 20, 30));
}
}
Run Code Online (Sandbox Code Playgroud)
将您的方法更改为:
public static int volume(final int i, final int j, final int k){
return i*j*k;
}
Run Code Online (Sandbox Code Playgroud)
会给你你想要的价值.
另外,请阅读@ eljenso的答案以获取更多详细信息.
你可能想要的是这个:
public static int volume(final int i, final int j, final int k){
this.length = i;
this.breadth = j;
this.height = k;
return length * breadth * height;
}
Run Code Online (Sandbox Code Playgroud)
由于10, 20, 30传递了值i, j, k,但是您没有将它们分配给您,因此遇到了问题length, breadth, height.
顺便说一句,static在这种情况下你并不需要.这对您的班级来说是更好的设计:
class Cube{
int length;
int breadth;
int height;
public Cube(int length, int breadth, int height) {
this.length = length;
this.breadth = breadth;
this.height = height;
}
public int volume(){
return length * breadth * height;
}
}
Run Code Online (Sandbox Code Playgroud)
它可以使用如下:
public static void main(String[] args) {
Cube c = new Cube(10, 20, 30);
System.out.println(c.volume());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
591 次 |
| 最近记录: |