问题描述
这是操作说明: 显示所有三个帐户的名称和余额。使用 if 语句,打印名称和 拥有最大金额的银行帐户对象的余额(基于您的值) 选择)。您可能需要向 Bank 类添加其他方法(获取方法)。
这是我的代码:
import java.util.*;
public class Bank
{
public Bank()
{
double checkingBal = 0.0;
double savingsBal = 0.0;
}
public static void main(String[] args)
{
System.out.println("Problem 1");
Bank tom = new Bank();
Bank rohan = new Bank();
Bank parth = new Bank();
tom.setChecking(10000);
parth.setChecking(60000);
rohan.setChecking(700000);
larmo();
}
public void setChecking(double val)
{
double checkingBal = val;
}
public Bank larmo()
{
System.out.println(tom.getChecking());
System.out.println(rohan.getChecking());
System.out.println(parth.getChecking());
if (tom.getChecking()>parth.getChecking() && tom.getChecking()>rohan.getChecking())
{
System.out.println("Name: Tom,Balance: "+tom.getChecking());
}
if (parth.getChecking()>tom.getChecking() && parth.getChecking()>rohan.getChecking())
{
System.out.println("Name: Parth,Balance: "+parth.getChecking());
}
if (rohan.getChecking()>tom.getChecking() && rohan.getChecking()>parth.getChecking())
{
System.out.println("Name: Rohan,Balance: "+rohan.getChecking());
}
System.out.println("Congratulations to the richest man in the bank");
}
public double getChecking()
{
return checkingBal;
}
}
我收到此错误: 不能从静态上下文中引用非静态方法 larmo()
为什么,我该怎么做才能解决这个问题。
解决方法
在您的情况下,您应该将方法更改为 public static void larmo()
static
因为该方法不需要访问 Bank 实例。这也允许从静态上下文调用它。
void
因为您没有从方法中 return
任何值。
我们无法直接从静态成员访问非静态成员。
如果你想访问那个larmo method():
- 或者您应该将 larmo 方法设为静态
- 或者,创建 Bank 类的实例并使用该实例调用 larmo 方法