我已经在这里展示了完整的类,以防我需要特别修改什么。我想在主方法中调用"power“方法,正如您在代码中看到的那样,但是它将无法工作,因为其中一个方法是静态的,另一个方法不是静态的。有谁知道解决这个问题的方法吗?所有的帮助都很感激!
public class Power
{
public int square(int x){
return x*x;
}
public int cube(int x){
return power(x, 3);
}
public int hypercube(int x){
return power(x, 4);
}
public int power(int x, int n)
{
if (n==1)
System.out.println(n);
if (n==2)
square(x);
if (n==3)
cube(x);
if (n==4)
hypercube(x);
}
public static void main(String[] args)
{
int x = 6;
Power p = new Power();
System.out.println( "The square of " + x + " is: " + power( x, 2 ) );
System.out.println( "The cube of " + x + " is: " + power( x, 3 ) );
System.out.println( "The hypercube of " + x +" is: " + power(x, 4));
}
}编辑:我已经做了修改,但是我在第15、26和34行中得到了一个堆栈溢出错误。这是修改后的代码。
public class Power{
public static int square(int x){
return x*x;
}
public static int cube(int x){
return power(x, 3);
}
public static int hypercube(int x){
return power(x, 4);
}
public static int power(int x, int n){
if (n==1){
System.out.println(n);
}
if (n==2){
square(x);
}
if (n==3){
cube(x);
}
if (n==4){
hypercube(x);
}
return x;
}
public static void main(String[] args){
int x = 6;
System.out.println( "The square of " + x +
" is: " + power( x, 2 ) );
System.out.println( "The cube of " + x +
" is: " + power( x, 3 ) );
System.out.println( "The hypercube of " + x +
" is: " + power( x, 4 ) );
}
}第15行是:
return power(x, 3);第26行是:
if (n==1){第34行是:
cube(x);发布于 2013-11-25 17:05:28
使所有的功能都是静态的。
提示:所有不访问类的非静态字段或函数的函数都可以是静态的。
在这种情况下,函数只使用它们的参数,因此可以是静态的。
发布于 2013-11-25 17:15:33
这取决于你的要求..。
在您介绍的情况下,它看起来更像是需要静态方法,而不是处理Power实例。
正如其他答案之一所述,如果不访问任何实例变量,则应将方法设置为static。
例如:
public static int power(int x, int n)
现在从main可以这样做:
System.out.println( "The square of " + x + " is: " + Power.power( x, 2 ) );
并废除Power p = new Power();
如果确实有人要求您使用Power对象作为实例。
它将非常简单,如:
System.out.println("The square of " + x + " is: " + p.power(x, 2));
如果你想写你自己的数学函数。停止并使用java.lang.Math,更多信息可以找到这里。
发布于 2015-01-06 12:59:52
是的你可以。
作为示例,请参阅下面的代码:
class Cal {
int cube(int x) {
return x * x * x;
}
public static void main(String args[]) {
//int result=Cal.cube(6);
//Cal q=new cal();
//q.cube(6);
System.out.println(Cal.cube(6));
}
}https://stackoverflow.com/questions/20198722
复制相似问题