【问题标题】:Non-static method referenced from a static method error message? [closed]从静态方法错误消息中引用的非静态方法? [关闭]
【发布时间】:2013-01-04 19:46:26
【问题描述】:

编写一个程序来计算单利,并且必须使用单独的方法来返回计算并进行计算。

public class Unit7B
{
   public static void main ( String [ ] args ) 
   {
       double p = Input.getDouble ("Enter the principal");
       double i = Input.getDouble ("Enter the interest rate");
       double n = Input.getDouble ("Enter the number of years");

       double result = simpleInterest( p, i, n); 
       System.out.println (result);
   }

   public double simpleInterest (double p, double i, double n)
   {
       return ( p * ( Math.pow ( 1.0 + i , n ) ));
   }
}

【问题讨论】:

  • 对不起 Java 和“simpeInterest (p, i , n);”据说是静态方法中引用的非静态方法

标签: java static


【解决方案1】:

您需要将simpleInterest标记为静态方法:

public static double simpleInterest (double p, double i, double n)
{
    return ( p * ( Math.pow ( 1.0 + i , n ) ));
}

这是因为非静态方法需要类实例,而静态方法不需要。为了使用您的非静态方法,您必须使用以下内容创建类:

Unit7B unit = new Unit7B();
unit.simpleInterest(p, i, n);

【讨论】:

  • 对不起,我是一个 java 新手,我该把那个代码块放在哪里?
  • 哪个代码块?您应该将方法更改为静态。
  • 您提供的代码:Unit7B unit = new Unit7B(); unit.simpleInterest(p, i, n);应该与主方法名称或其他方法交换吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-31
  • 1970-01-01
  • 2011-06-22
  • 1970-01-01
相关资源
最近更新 更多