如何解决从 getter setter 传递值
我想知道是否有办法从 getter setter 传递值。下面的代码将是我正在使用的示例。
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Sales {
private int transaction;
private int salesNum;
private String name;
private double amount;
private double commission;
Scanner input = new Scanner(System.in);
Sales sales = new Sales();
//default constructor
public Sales() {
transaction = 0;
salesNum = 0;
name = "";
amount = 0.0;
commission = 0.0;
}
//getter method
public int getTransaction() {
return transaction;
}
public int getSalesNum() {
return salesNum;
}
public String getName() {
return name;
}
public double getAmount() {
return amount;
}
//setter method
public void setTransaction() {
do {
System.out.println("Enter transaction number: ");
try {
transaction = Integer.parseInt(input.nextLine());
break;
} catch (NumberFormatException e) {
}
} while (true);
}
public void setSalesNum() {
do {
System.out.println("Enter sales number: ");
try {
salesNum = Integer.parseInt(input.nextLine());
break;
} catch (NumberFormatException e) {
}
} while (true);
}
public void setName() {
do {
System.out.println("Enter name: ");
name = input.nextLine();
Pattern pattern = Pattern.compile("[a-zA-Z]+");
Matcher matcher = pattern.matcher(name);
if (name.matches("[a-zA-Z]+")) {
break;
}
} while (true);
}
public void setAmount() {
do {
System.out.println("Enter amount: ");
try {
amount = Double.parseDouble(input.nextLine());
break;
} catch (NumberFormatException e) {
}
} while (true);
}
public double commission(double commission) {
this.commission= sales.getAmount();
return this.commission;
}
//This was what I am trying to do
/* public void rate() {
if(getAmount() >= 0 || getAmount() <= 999) {
commission = 0;
}
else if(getAmount() >= 1000 || getAmount() <= 1999 ) {
commission = 0.02;
}
else if(getAmount() >= 2000 || getAmount() <= 2999) {
commission = 0.03;
}
else {
commission = 0.05;
}
}*/
@Override
public String toString() {
setTransaction();
setSalesNum();
setName();
setAmount();
System.out.print(this.commission);//I am using this to test if it will show the output of commission
return String.format("%s,your transaction number and sales number are %d and %d respectively. Total amount is %.2f.\n",this.getName(),this.getTransaction(),this.getSalesNum(),this.getAmount());
}
}
这将打印出在驱动程序类中调用时的数量。但是,我想将 this.getAmount() 的值传递给一个参数。基本上我想要做的是获得 double value = this.getAmount() 这样我就可以将 value 放入 if else 语句中以使其成为 if(value >= 0 && value
我希望我的解释是可以理解的。提前致谢。
P.S 我最近刚问过这个问题,但这最终给了我 StackOverflowError。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。