我正在尝试创建一个类Tax
,它使用扫描程序变量来获取用户的工资和税率,并使用用户的输入提供税后工资。
我得到的错误是set-method不能用于使用scanner变量。请提出解决方案。
代码如下: -
package new_version;
import java.util.Scanner;
class Tax
{
private int salary;
private double rate;
private double posttaxsal;
public int getSalary()
{
return salary;
}
public double getRate()
{
return rate;
}
public void setSalary(int newSalary)
{
salary = newSalary;
}
public void setRate(double newRate)
{
rate = newRate;
}
public double posttaxsal()
{
posttaxsal = salary - (salary*rate);
return posttaxsal;
}
}
public class Taxusinginput {
public static void main(String[] args) {
Tax test = new Tax();
Scanner s = new Scanner(System.in);
Scanner r = new Scanner(System.in);
test.setSalary(s);
test.setRate(r);
}
}
答案 0 :(得分:0)
setSalary
需要一个int参数,而不是Scanner
。您应该将int
值传递给它。
例如:
test.setSalary(s.nextInt());
setRate
同样如此。
除此之外,没有理由创建两个Scanner实例。
public static void main(String[] args) {
Tax test = new Tax();
Scanner s = new Scanner(System.in);
test.setSalary(s.nextInt());
test.setRate(s.nextDouble());
}
答案 1 :(得分:0)
正如我之前的评论中所提到的,你的函数期望是int和double,而不是Scanner对象
使用Scanner#nextInt()
和Scanner.nextDouble()
。
工作示例:
import java.util.Scanner;
public class Taxusinginput {
public static void main(String[] args) {
Tax test = new Tax();
// Use only one scanner
Scanner sc = new Scanner(System.in);
System.out.print("Enter salary: ");
test.setSalary(sc.nextInt());
System.out.print("Enter rate: ");
test.setRate(sc.nextDouble());
System.out.println("Post-tax salary: " +
test.posttaxsal());
sc.close();
}
}
class Tax {
private int salary;
private double rate;
private double posttaxsal;
public int getSalary() {
return salary;
}
public double getRate() {
return rate;
}
public void setSalary(int newSalary) {
salary = newSalary;
}
public void setRate(double newRate) {
rate = newRate;
}
public double posttaxsal() {
posttaxsal = salary - (salary * rate);
return posttaxsal;
}
}
<强>输入/输出:强>
Enter salary: 1000
Enter rate: 0.02
Post-tax salary: 980.0