gpt4 book ai didi

java - 将值从不同的函数传递到单个对象

转载 作者:行者123 更新时间:2023-12-02 04:52:27 26 4
gpt4 key购买 nike

我有两个方法
第一个方法有一个对象作为返回类型
第二个方法有整数作为返回类型
我在第一种方法中有一些值,在第二种方法中有一些值
我想做的就是将所有这些值传递给一个对象。
但问题是只有第一个方法的值正在传递,而第二个方法的值没有传递。
我正在练习封装
下面是两个文件和OUTPUT的代码。

//Employee.java file
import java.util.*;
class Employee
{
private int employeeId;
private String employeeName;
private double salary;
private double netSalary;

/*public Employee()
{

}*/
public void setEmployeeId(int a)
{
employeeId = a;
}
public void setEmployeeName(String b)
{
employeeName = b;
}
public void setSalary(double c)
{
salary=c;
}
public int getEmployeeId()
{
return employeeId;
}
public String getEmployeeName()
{
return employeeName;
}
public double getSalary()
{
return salary;
}
public void calculateNetSalary(int pfpercentage)
{
netSalary = salary-((salary*pfpercentage)/100);
}
public double getNetSalary()
{
return netSalary;
}
}
import java.util.*;
class Main
{
public static Employee getEmployeeDetails(Employee e)//1st Method
{
Scanner sc=new Scanner (System.in);
try
{
System.out.println("Enter Id:");
e.setEmployeeId(sc.nextInt());
sc.nextLine();
System.out.println("Enter Name:");
e.setEmployeeName(sc.nextLine());
System.out.println("Enter salary:");
e.setSalary(sc.nextDouble());
sc.nextLine();

}catch(Exception e1){System.out.println("Invalid Input");}
return e;
}
public static int getPFPercentage()//2nd Method
{
Employee e = new Employee();
int pf=0;
Scanner sc1=new Scanner(System.in);
try
{
System.out.println("Enter PF percentage:");
pf=sc1.nextInt();
e.calculateNetSalary(pf);

}catch(Exception e1){System.out.println("Invalid Input");}
return pf;
}
public static void main(String args[])
{
Employee e = new Employee();
getEmployeeDetails(e);
getPFPercentage();
System.out.println();
System.out.println("Id : "+e.getEmployeeId());
System.out.println("Name : "+e.getEmployeeName());
System.out.println("Salary : "+e.getSalary());
System.out.println("Net Salary : "+e.getNetSalary());

}

}
OUTPUT
Enter Id:
101
Enter Name:
Harry
Enter salary:
20000
-------------1st method is used to take above input
Enter PF percentage:
7
-------------2nd method is used to take only PF percentage input

Id : 101
Name : Harry
Salary : 20000.0
Net Salary : 0.0

净工资的计算在文件 Employee.java 中,函数名称为“calculateNetSalary”

最佳答案

在调用方法getNetSalary()之前,您尚未计算netSalary

public void calculateNetSalary(int pfpercentage) //This function should be called first.
{
netSalary = salary-((salary*pfpercentage)/100);
}
public double getNetSalary()
{
return netSalary;
}

查看下面的代码以更好地理解:

System.out.println("Salary : "+e.getSalary());
e.calculateNetSalary(5); //Add this line and you will get the required output.
System.out.println("Net Salary : "+e.getNetSalary());

关于java - 将值从不同的函数传递到单个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56426668/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com