我想知道是否有办法从 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 <= 100) { percent = 0.05; }.所需的输出是我在提示输入金额时输入 50,然后它会检查它是否在 0-100 之间,然后根据 if else 和输入,百分比将变为 0.05,依此类推。然后显示百分比。
我希望我的解释是可以理解的。提前致谢。
P.S 我最近刚问过这个问题,但这最终给了我 StackOverflowError。