passing values from different function to a single object - java

I have two methods 1st method has a object as a return type and 2nd method has integer as a return type.
I have some values in 1st method and some values in 2nd method
All i want to do is pass all these values to a single object.
But the problem is only values of 1st method is passing and the values from second method is not passing.I am practicing Encapsulation
Below is the code of two files and 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
Calculation of Net salary is in file Employee.java function name "calculateNetSalary"

You have not calculated netSalary before calling method getNetSalary();
public void calculateNetSalary(int pfpercentage) //This function should be called first.
{
netSalary = salary-((salary*pfpercentage)/100);
}
public double getNetSalary()
{
return netSalary;
}
Look below code for better understanding:
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());

The problem is inside getPFPercentage() method you are creating a new Employee object. You should use the same object created in the main method.
public static int getPFPercentage(Employee e)//2nd Method
{
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(e);
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());
}

In the 'getPFPercentage' method you are creating a new object but in the main method you are using a different object.
Pass the object that you have created in the main method to the getPFPercentage method
Change you getPFPercentage signature to
'public static int getPFPercentage(Employee e)'
Remove the object creation line in the getPFPercentage method
and call this method from the main method
- getPFPercentage(e)

Related

I am getting error logical in method getData() in my Java homework

Here is my assignment:
Create a class named TestLease whose main() method declares four Lease objects. Call a getData() method three times. Within the method, prompt a user for values for each field for a Lease, and return a Lease object to the main() method where it is assigned to one of main()’s Lease objects. Do not prompt the user for values for the fourth Lease object, but let it continue to hold the default values.
Then, in main(), pass one of the Lease objects to the showValues() method that displays the data. Then call the addPetFee() method using the passed Lease object and confirm that the fee explanation statement is displayed. Next, call the showValues() method for the Lease object again and confirm that the pet fee has been added to the rent. Finally, call the showValues() method with each of the other three objects; confirm that two hold the values you supplied as input and one holds the constructor default values.
My results is correct as the homework requires. But my professor says that I have a logical error at getData() method. I tried to find the error but could not figure out.
class Lease {
private String name;
private int aptNumber;
private double rent;
private int term;
private static final int FEE = 10;
public Lease() {
name = "XXX";
aptNumber = 0;
rent = 1000.0;
term = 12;
}
public void setName(String tenant) {
name = tenant;
}
public void setAptNumber(int apt) {
aptNumber = apt;
}
public void setRent(double monthRent) {
rent = monthRent;
}
public void setTerm(int t) {
term = t;
}
public String getName() {
return name;
}
public int getAptNumber() {
return aptNumber;
}
public double getRent() {
return rent;
}
public int getTerm() {
return term;
}
public void addPetFee() {
rent = rent + FEE;
explainPetPolicy();
}
public static void explainPetPolicy() {
System.out.println("A pet fee of $10 is added to your monthly rent and: ");
}
}
import java.util.Scanner;
class TestLease
{
public static void main (String args[])
{
Lease lease1 = getData();
showValues(lease1);
Lease lease2 = getData();
showValues(lease2);
Lease lease3 = getData();
showValues(lease3);
lease3.addPetFee();
showValues(lease3);
Lease lease4 = new Lease();
showValues(lease4);
}
public static void showValues(Lease ls)
{
System.out.println("\n\nYour lease results:" +
"\nName : " + ls.getName() +
"\nApartment : " + ls.getAptNumber() +
"\nRent : " + ls.getRent() +
"\nTerm : " + ls.getTerm() + "\n");
}
public static Lease getData()
{
Lease sample = new Lease();
Scanner userInput = new Scanner(System.in);
System.out.println("Please enter your name:");
String sampleName = userInput.nextLine();
sample.setName(sampleName);
System.out.println("Please enter your apartment number:");
int sampleAptNumber = userInput.nextInt();
sample.setAptNumber(sampleAptNumber);
System.out.println("Please enter your monthly rent amount:");
double sampleRent = userInput.nextDouble();
sample.setRent(sampleRent);
System.out.println("Please enter the term of your lease in months:");
int sampleTerm = userInput.nextInt();
sample.setTerm(sampleTerm);
userInput.nextLine();
return sample;
}
}

validate private variable of another class when giving input

hello I have written code where it takes book details using setter method and displaying details using getter method. When user enters the input it has to enter three details.
Book NameBook PriceAuthor Name
I want to check if user has given any negative value or Zero value in Book Price.
How do I do that? Below is the code. I am practicing Encapsulation problem
//Book.java file
class Book
{
private String bookName;
private int bookPrice;
private String authorName;
public String getBookName()
{
return bookName;
}
public int getBookPrice()
{
return bookPrice;
}
public String getAuthorName()
{
return authorName;
}
public void setBookName(String a)
{
bookName=a;
}
public void setBookPrice(int b)
{
bookPrice=b;
}
public void setAuthorName(String c)
{
authorName=c;
}
}
//TestBook.java file
import java.util.*;
class TestBook
{
public static void main(String args[])
{
Book bobj = new Book();
Scanner sc = new Scanner(System.in);
try
{
System.out.println("Enter the Book name:");
bobj.setBookName(sc.nextLine());
System.out.println("Enter the price:");
bobj.setBookPrice(sc.nextInt());
sc.nextLine();
System.out.println("Enter the Author name:");
bobj.setAuthorName(sc.nextLine());
System.out.println();
System.out.println("Book Details");
System.out.println("Book Name :"+bobj.getBookName());
System.out.println("Book Price :"+bobj.getBookPrice());//should not be -ve or 0
System.out.println("Author Name :"+bobj.getAuthorName());
}
catch(Exception e)
{
System.out.println("Invalid Input");
}
}
}
You should put this check in your setter method to check if it is greater than zero. For example:
public void setBookPrice(int b)
{
if(b>0)
bookPrice=b;
else
{
throw new IllegalArgumentException("b must be positive")
}
}
Above code will prevent setting of negative and zero price. You can replace exception throwing code with your own handling.
If you are practising encapsulation I suggest creating a specific validation method for the price so this can be easily modified without changing the public interface.
public boolean isValidPrice() {
return bookPrice > 0;
}
This can now be checked with
if (!bobj.isValidPrice()) {
//error handling
}
And if the validation rules for price would change the calling code will remain unchaged

If called from Main class returns empty value

Main class:
package com.home.dhe;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Display q = new Display();
q.getinfo();
Getname z = new Getname();
z.print();
}
}
Display class:
public class Display extends Getname{
public void getinfo() {
System.out.println("Enter name");
Scanner sc = new Scanner(System.in);
String d = sc.next();
System.out.println("Marks?");
int c = sc.nextInt();
Getname z = new Getname();
z.change(d, c);
}
}'
Getname class:
public class Getname {
private int marks;
private String name;
public void change(String a, int b){
name = a;
marks = b;
}
public void print(){
System.out.println("Student info");
System.out.println("marks:"+marks);
System.out.println("Name:"+name);
}
}
My problem is when I call the print() method (from the Getname class)
from Main class it returns a null value. But when I call it in from another class it works.
Can someone tell me why?
You are discarding the Getname instance created by q.getInfo(). What you probably want to do is return the Getname instance from q.getInfo() and use that to print.
public class Display extends Getname {
public Getname getinfo() {
System.out.println("Enter name");
Scanner sc = new Scanner(System.in);
String d = sc.next();
System.out.println("Marks?");
int c = sc.nextInt();
Getname z = new Getname();
z.change(d, c);
return z;
}
}
Then in the main method.
public static void main(String[] args) {
// TODO Auto-generated method stub
Display q = new Display();
Getname z = q.getinfo();
z.print(); // This will print the values set by q.getInfo()
}
Overall, I think you may have some design problems that should be fixed.
both marks,name instant variables in class Getname need to be initialized, otherwise, the default values will be assigned to them : zero for integer and null for String.

Why my variables cannot receive a value (interface)

I having a problem to send a value on the variables. Why my variable cannot receive the value when I input a value? I've no idea to do...
import java.io.*;
public class StudentApp {
public static void main (String [] args) throws IOException {
student studentObject = new GradeResult();
studentObject.getName();
student studentObject2 = new GradeResult();
studentObject2.getIdNum();
student studentObject3 = new GradeResult();
studentObject3.getMark();
student studentObject4 = new GradeResult();
studentObject4.setName();
student studentObject5 = new GradeResult();
studentObject5.setIdNum();
student studentObject6 = new GradeResult();
studentObject6.setMark();
student studentObject7 = new GradeResult();
studentObject7.showGrade();
student studentObject8 = new GradeResult();
studentObject8.showResult();
}
interface StudentInterface{
void getName() throws IOException;
void getIdNum()throws IOException;
void setName();
void setIdNum();
void getMark()throws IOException;
void setMark();
}
interface student extends StudentInterface{
void showResult();
void showGrade();
}
class GradeResult implements student {
String name ,name2 ,name3;
int a ,mark;
public void getName () throws IOException {
InputStreamReader inStream = new InputStreamReader(System.in);
BufferedReader stdin = new BufferedReader(inStream);
System.out.print("Please Input Your Name :");
name = stdin.readLine();
}
public void getIdNum()throws IOException {
BufferedReader stdin=new BufferedReader (new InputStreamReader(System.in));
System.out.print("Please Input Your ID Number :");
name2 = stdin.readLine();
a = Integer.parseInt(name2);
}
public void setName() {
System.out.print("Your Name :"+name);
}
public void setIdNum() {
System.out.print("\nYour ID Number :"+name2);
}
public void getMark()throws IOException {
BufferedReader stdin=new BufferedReader (new InputStreamReader(System.in));
System.out.print("Please Input Your Mark :");
name3 = stdin.readLine();
mark = Integer.parseInt(name3);
}
public void setMark() {
System.out.print("\nYour Mark :"+mark);
}
public void showResult() {
if ((mark>=40)&&(mark<=100)) {
System.out.print("\nYou Are PASS");
} else {
System.out.print("\nYou Are FAIL");
}
}
public void showGrade() {
if((mark>=80)&&(mark<=100)) {
System.out.print("\nYour Grade Is A");
} else if ((mark>=65)&&(mark<=80)) {
System.out.print("\nYour Grade Is B");
} else if ((mark>=50)&&(mark<=65)) {
System.out.print("\nYour Grade Is C");
} else if ((mark>=40)&&(mark<=50)) {
System.out.print("\nYour Grade Is D");
} else {
System.out.print("\nYour Grade Is E");
}
}
}
I'm not sure which one is my mistake. Should I need to use object reference to receive the value or just call as usual on main method.
Best working solution is to do the following in your GradeResult class
private static String name, name2, name3;
private static int a, mark;
This will work..!
The output:
Please Input Your Name :Mohammad
Please Input Your ID Number :10001
Please Input Your Mark :85
Your Name :Mohammad
Your ID Number :10001
Your Mark :85
Your Grade Is A
You Are PASS
You are creating new objects everytime, therefore your results get put in different objects.
Try this:
student studentObject = new GradeResult();
studentObject.getName();
studentObject.setName();
EDIT: In case you didn't know it, instance variables values are held within an object. So all your different objects (of the same class) will have different name, name2, name3, etc. The objects from which you call the System.out.println(...) methods have uninitialized instance variables (name, name2, name3) and hence will not print any values for those.
create object set value for that object and access value from same object. In your case you are setting value to some object and accessing data from other object that is why you are getting null for some fields.
public static void main (String [] args) throws IOException{
student studentObject = new GradeResult();
studentObject.getName();
studentObject.getIdNum();
studentObject.getMark();
studentObject.setName();
studentObject.setIdNum();
studentObject.showGrade();
studentObject.showResult();
}

infile class. Constructor undefined

It keeps telling me that my constructor Pet is undefined. Any ideas?
I've tried defining Pet in my main method prior to the while loop, but it gives me the same issue.
import java.util.*;
import java.io.*;
public class ReadPets
{
public static void main (String[] args)
{
ArrayList <Pet> petList = new ArrayList <Pet>();
Scanner inFile = null;
String name;
Pet p;
try
{
inFile = new Scanner
(new FileInputStream ("pets.txt"));
}
catch(FileNotFoundException e)
{
System.out.println("problem opening file.");
System.exit(0);
}
while (inFile.hasNextLine())
{
name = inFile.nextLine();
p = new Pet(name); // here is where my error is
petList.add(p);
}
inFile.close();
}
}
Here is my Pet class.
public class Pet
{
private String name;
private int age; //in years
private double weight; //in pounds
/**
This main is just a demonstration program.
*/
public static void main(String[] args)
{
Pet myDog = new Pet( );
myDog.set("Fido", 2, 5.5);
myDog.writeOutput( );
System.out.println("Changing name.");
myDog.set("Rex");
myDog.writeOutput( );
System.out.println("Changing weight.");
myDog.set(6.5);
myDog.writeOutput( );
System.out.println("Changing age.");
myDog.set(3);
myDog.writeOutput( );
}
public void writeOutput( )
{
System.out.println("Name: " + name);
System.out.println("Age: " + age + " years");
System.out.println("Weight: " + weight + " pounds");
}
public void set(String newName)
{
name = newName;
//age and weight are unchanged.
}
public void set(int newAge)
{
if (newAge <= 0)
{
System.out.println("Error: illegal age.");
System.exit(0);
}
else
age = newAge;
//name and weight are unchanged.
}
public void set(double newWeight)
{
if (newWeight <= 0)
{
System.out.println("Error: illegal weight.");
System.exit(0);
}
else
weight = newWeight;
//name and age are unchanged.
}
public void set(String newName, int newAge, double newWeight)
{
name = newName;
if ((newAge <= 0) || (newWeight <= 0))
{
System.out.println("Error: illegal age or weight.");
System.exit(0);
}
else
{
age = newAge;
weight = newWeight;
}
}
public String getName( )
{
return name;
}
public int getAge( )
{
return age;
}
public double getWeight( )
{
return weight;
}
}
Your Pet class does not have a constructor that takes a String which is what you are trying with this line
p = new Pet(name)
Either make one or do something similar to the demonstration, which is make the new Pet instance and then call set("Name") on this instance
Like:
p = new Pet();
p.set(name);
I do not see any constructors in your Pet class which means that Java will provide a default (no argument) constructor for you.
This is why the following statement is OK:
Pet myDog = new Pet( );
The statement that you have a problem with uses a constructor with an argument, that you have not defined.
You will need either to create such constructor (Pet(String name) {...}) or change your logic to use default constructor and your set() method.
Be warned as soon as you define any constructor, Java will no longer create a default constructor for you, so you will need to do it yourself.
You required to write one parametrized constructor in our Pet class with one String.

Categories