我正在尝试创建一个银行帐户程序,用户可以在其中输入储蓄帐户的“ s”或“ S”帐户类型。他们还可以为支票帐户输入“ c”或“ C”。我在让用户输入通过getter / setter方法运行,然后在输出中根据输入返回字符串“ Savings”或“ Checking”时遇到问题。
package com.company;
import javax.swing.*;
public class Main {
public static void main(String[] args) {
BankAccount myBank = new BankAccount();
myBank.setAccountType(JOptionPane.showInputDialog("please enter an account type"));
JOptionPane.showMessageDialog(null, "Account Number: " + "\nAccount Type: " + myBank.getAccountType() +"\nMinimum Balance: "+ "\nBalance Before Interest and Fees: " + "\n\nNew Balance:\n");
}
}
BankAccount
类
package com.company;
public class BankAccount {
private int accountNumber;
private String accountType;
private double minSavings = 2500;
private double minChecking = 1000;
private double currentBalance;
public BankAccount(){ }
public String getAccountType () {
return this.accountType;
}
public void setAccountType (String please_enter_an_account_type) {
if (accountType == "S" || accountType == "s") {
this.accountType = "Savings";
}
else if (accountType == "C" || accountType == "c") {
this.accountType = "Checking";
}
}
}
答案 0 :(得分:2)
您的setAccountType
方法代码应如下所示:
public void setAccountType (String accountType)
{
if (accountType.equalsIgnoreCase("S"))
{
this.accountType = "Savings";
}
else if (accountType.equalsIgnoreCase("C"))
{
this.accountType = "Checking";
}
}
这将解决问题。
参考:== and equals()
之间的区别:
What is the difference between == vs equals() in Java?
我已经使用equalsIgnoreCase()
来检查小写和大写值。
答案 1 :(得分:1)
String是一个Java对象,使用==
运算符比较两个Java对象引用仅在两个引用都引用同一对象时才返回true。这里if
中的“ s”和setter中的输入字符串“ s”指的是不同的对象。因此,要使其正常工作,您需要使用String的equals
方法,该方法比较值而不是对象参考。
public void setAccountType (String accountType)
{
if (accountType.toLowerCase().equals("s"))
{
this.accountType = "Savings";
}
else if (accountType.toLowerCase().equals("c"))
{
this.accountType = "Checking";
}
}