BinarySearch on Object Array List in Java - java

I am trying to perform binary search on an object array list. The user must type in admin number to perform search. Here is my code :
File Controller class to read file from .text file
public class FileController extends StudentApp{
private String fileName;
public FileController() {
String fileName = "student.txt";
}
public FileController(String fileName) {
this.fileName = fileName;
}
public ArrayList<String> readLine() {
ArrayList<String> studentList = new ArrayList<String>();
try {
FileReader fr = new FileReader(fileName);
Scanner sc = new Scanner(fr);
while (sc.hasNextLine()) {
studentList.add(sc.nextLine());
}
fr.close();
} catch (FileNotFoundException exception) {
System.out.println("File " + fileName + " was not found");
} catch (IOException exception) {
System.out.println(exception);
}
return studentList;
}
Student Class with all the setter & getter and compareTo method
public Student(String adminNo, String name, GregorianCalendar birthDate) {
this.adminNo = adminNo;
this.name = name;
this.birthDate = birthDate;
}
public Student(String record) {
Scanner sc = new Scanner(record);
sc.useDelimiter(";");
adminNo = sc.next();
name = sc.next();
birthDate = MyCalendar.convertDate(sc.next());
test1 = sc.nextInt();
test2 = sc.nextInt();
test3 = sc.nextInt();
}
public String toString(){
return (adminNo + " " + name + " " + MyCalendar.formatDate(this.birthDate));
}
public static ArrayList<Student> readStudent(String file) {
FileController fc = new FileController(file);
ArrayList<Student> recs = new ArrayList<Student>();
ArrayList<String> recsReturn = new ArrayList<String>();
recsReturn = fc.readLine();
for (int index = 0; index < recsReturn.size(); index++) {
String input = recsReturn.get(index);
recs.add(new Student(input));
}
return recs;
}
public int compareTo(Student s) {
return Compare(this, s);
}
public int Compare(Student s1, Student s2){
if(s1.getAdminNo().equals(s2.getAdminNo())) {
return 0;
}else{
return 1;
}
}
Executable main method lies here, in StudentSearch Class
public static void main(String [] args){
Scanner sc = new Scanner(System.in);
ArrayList <Student> studentList = new ArrayList <Student> ();
studentList = Student.readStudent("student.txt");
Collections.sort(studentList);
System.out.println("Enter student admin number: ");
String searchAdminNo = sc.next();
int pos = Collections.binarySearch(studentList, new Student(searchAdminNo));
System.out.println(pos);
}
I want to perform search by using the user input admin number. However, here's the error message:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at StudentGradeApps.Student.<init>(Student.java:22)
at StudentGradeApps.StudentSearch.main(StudentSearch.java:14)
I think the problem lies at the compareTo method and my binary search. Because when I removed them, my program can get the array list fine. The error only occurs when I try to perform search on my object list. Any help would be appreciated.
Thanks in advance.

As the error message say, the exception is occurring within the Student constructor -
public Student(String record) {
Scanner sc = new Scanner(record);
sc.useDelimiter(";");
adminNo = sc.next();
name = sc.next();
birthDate = MyCalendar.convertDate(sc.next());
test1 = sc.nextInt();
test2 = sc.nextInt();
test3 = sc.nextInt();
}
You are invoking the constructor here -
int pos = Collections.binarySearch(studentList, new Student(searchAdminNo));
searchAdminNo probably doesn't have that many tokens (delimited by ;) as you are reading in the constructor.

Related

Is there any way to store the elements present in the file to the to the array of the object in java

The program is giving correct output when System.out.println(mem[i].memName); but the array of class "member" is giving output (alex alex alex alex) i.e of the last line of the file (mentioned at the END of the CODE)
it should give all the names listed in the file.
import java.io.*;
import java.util.*;
class member//CLASS TO BE USED AS ARRAY TO STORE THE PRE REGISTERED MEMBERS FED INSIDE
{ //THE FILE "member.txt"
static int memId;
static String memName, memEmail, memPh, date;
}
public class entry// file name
{
static DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
static LocalDateTime now = LocalDateTime.now();
static Scanner input = new Scanner(System.in);
static member[] mem = new member[100];
static trainer[] tr = new trainer[100];
static FileWriter fwriter = null;
static BufferedWriter bwriter = null;
static FileReader fread = null;
static BufferedReader bread = null;
static void memberEntry() {
int i = 0;
System.out.println("NEW MEMBER IS BEING ADDED");
try {
fwriter = new FileWriter("C:\\Users\\itisa\\OneDrive\\Desktop\\GYM
PROJECT\\member.txt
",true);
bwriter = new BufferedWriter(fwriter);
System.out.println("Member ID is being automatically genrated");
int autoID = 101 + getMemberRecords();//Fetching the number of members so that ID can
//Be genrated automatically
i = autoID % 100;//jumping toward the next loaction location
System.out.println("Member ID of new member is" + autoID);
mem[i].memId = autoID;
System.out.print("Enter the name of the member:");
mem[i].memName = input.next();
System.out.print("Enter the email address of memeber:");
mem[i].memEmail = input.next();
System.out.print("Enter the contact number of memeber:");
mem[i].memPh = input.next();
System.out.println("Date has been feeded automatically:" + dtf.format(now));
mem[i].date = dtf.format(now);
bwriter.write(String.valueOf(mem[i].memId));
bwriter.write("|");
bwriter.write(mem[i].memName);
bwriter.write("|");
bwriter.write(mem[i].memEmail);
bwriter.write("|");
bwriter.write(mem[i].memPh);
bwriter.write("|");
bwriter.write(mem[i].date);
bwriter.write("\n");
System.out.println("MEMBER CREATED SUCCESSFULLY");
System.out.println("---------------------------------------");
bwriter.close();
} catch (IOException e) {
System.out.print(e);
}
}
static int getMemberRecords() {
int count = 0, i = 0;
try {
fread = new FileReader("C:\\Users\\itisa\\OneDrive\\Desktop\\GYM PROJECT\\member.txt");
bread = new BufferedReader(fread);
String lineRead = null;
while ((lineRead = bread.readLine()) != null)//Just to get to know the number of member
//alreadyinside the file
{
String[] t = lineRead.split("\\|");
mem[i].memId = Integer.parseInt(t[0]);
mem[i].memName = t[1];
mem[i].memEmail = t[2];
mem[i].memPh = t[3];
mem[i].date = t[4];
i++;
count++;
}
System.out.println(mem[0].memName);//should print the 1st name present in the name
//i.e, RAVI
} catch (IOException e) {
System.out.println(e);
}
return count;
}
public static void main(String[] args) throws IOException {
System.out.println("Total number of accounts:" + getMemberRecords());
}
}
Elements stored in the file:
101|RAVI|itisadi23#gmai.com|9102019656|2020/04/30
102|aditya|adi#gmail.com|9386977983|2020/04/30
103|anurag|anu#ymail.com|10000000000|2020/04/30
104|alex|alex123#mail.com|2829578303|2020/04/30
Expected output:
RAVI
Total number of accounts = 4
My output:
alex
Total number of accounts=4
In Short it is giving last name as output no matter what index number is given to fetch the data.
Your member class members must not be static, if they are, they're shared by every member class object.
The other problem is that your member array nodes are not being initialized, you'll need:
Live demo
class member
{
int memId; //non-static
String memName, memEmail, memPh, date; //non-static
}
and
//...
while ((lineRead = bread.readLine()) != null) {
String[] t = lineRead.split("\\|");
mem[i] = new member(); // initialize every node
mem[i].memId = Integer.parseInt(t[0]);
mem[i].memName = t[1];
mem[i].memEmail = t[2];
mem[i].memPh = t[3];
mem[i].date = t[4];
i++;
count++;
}
System.out.println(mem[0].memName);
//...
Output:
RAVI
Note that you can use ArrayList or other java collection.

How to copy by reference and deserialize a list of objects in java?

So I am a beginner in Java and my professor has us doing this assignment and I've been looking around but I can't seem to find the right answer for my type of code. We had to create a class file and then a public class file to test it.
import java.io.Serializable;
public class Person implements Serializable {
String Fname = new String();
String MI = new String();
String Lname = new String();
String age = new String();
String gpa = new String();
// int age = 20;
// double gpa = 0.0;
String Major = new String();
String answer;
//***********************************************
// The methods declared will go below
// The first method is for the first name
public String getFname() {
return Fname;
}
public void setFname(String Fname) {
this.Fname = Fname;
}
// This method is for the Middle Initial
public String getMI() {
return MI;
}
public void setMI(String MI) {
this.MI = MI;
}
// This method is for the Last name
public String getLname() {
return Lname;
}
public void setLname(String Lname) {
this.Lname = Lname;
}
// This method is for the Age
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
// This method is for the GPA
public String getGpa() {
return gpa;
}
public void setGpa(String gpa) {
this.gpa = gpa;
}
// This method is for the Major
public String getMajor() {
return Major;
}
public void setMajor(String Major) {
this.Major = Major;
}
}
The Person.java code is Serializable is supposed to be written to a fhm file and then Deserialized in order to print the contents of the file into terminal (Unix). Below is the main code which is the TestPerson code that will read the class Person code.
import java.util.Scanner;
import java.io.*;
public class TestPerson {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Person[] Peeps = new Person[3];
Peeps[0] = new Person();
Peeps[1] = new Person();
Peeps[2] = new Person();
Scanner scan = new Scanner(System.in);
String Answer = new String();
String age1 = new String();
String gpa1 = new String();
for (int i = 0; i < Peeps.length - 1; i++) {
// for (int i = 0; i < 3; i++) {
System.out.print("What is the First Name? ");
Answer = scan.nextLine();
Peeps[i].setFname(Answer);
System.out.print("What is MI? ");
Answer = scan.nextLine();
Peeps[i].setMI(Answer);
System.out.print(" What is Last Name? ");
Answer = scan.nextLine();
Peeps[i].setLname(Answer);
System.out.print(" What is the Age? ");
age1 = scan.nextLine();
int age = Integer.parseInt(age1);
// age = scan.nextInt();
Peeps[i].setAge(age1);
System.out.print(" What is the GPA? ");
gpa1 = scan.nextLine();
double gpa = Double.parseDouble(gpa1);
Peeps[i].setGpa(gpa1);
System.out.print(" What is the Major? ");
Answer = scan.nextLine();
Peeps[i].setMajor(Answer);
}
for (int i = 0; i < 3; i++) {
System.out.print(Peeps[i]);
}
try {
FileOutputStream fileOut = new FileOutputStream("Peeps.fhm");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(Peeps);
out.close();
fileOut.close();
System.out.println("\nSerialization Successful\n");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fileIn = new FileInputStream("Peeps.fhm");
ObjectInputStream in = new ObjectInputStream(fileIn);
System.out.println("Deserialized Data: \n" + in.readObject().toString());
in.close();
fileIn.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
My professor wants me to prompt the user to enter data for two of the Person objects at the Terminal and then copy the reference to one of two populated Persons to the last Person. Then the program will write all three Persons to a disk file with the extension of ".fhm" (Which I have completed). My question is how do I copy the reference? My second question is also how do I properly deserialize the file because when I run it, it works but the issue that pops up is that it tells me this:
Deserialized Data:
[LPerson;#5e481248
He wants it to print the information that was inputted by the user. I checked the fhm file that it writes to and it gathers all the information so I'm not sure what I'm doing wrong. Any help would be appreciated guys, sorry the post is kind of long. Thanks in advance.
I'm not sure what you meant by the "copy the reference" part.
The deserialization seems to be working well.
But in your code you're effectively just calling .toString() to print an array, which is probably not what you want.
You probably want to iterate over the items and print them one by one:
FileInputStream fileIn = new FileInputStream("Peeps.fhm");
ObjectInputStream in = new ObjectInputStream(fileIn);
Person[] peeps = in.readObject();
System.out.println("Deserialized Data:");
for (Person person : peeps) {
System.out.printf("First Name: %s MI: %s Last Name: %s%n",
person.getFname(), person.getMI(), person.getLname());
}
Your object is basically a Java array. To print it out, you could use:
System.out.println("Deserialized Data: \n" + Arrays.toString(in.readObject()));

Scanner from file doesn't seem to be reading file

I'm doing a Phone Directory project and we have to read from a directory file telnos.txt
I'm using a Scanner to load the data from the file telnos.txt, using a loadData method from a previous question I asked here on StackOverflow.
I noticed attempts to find a user always returned Not Found, so I added a few System.out.printlns in the methods to help me see what was going on. It looks like the scanner isn't reading anything from the file. Weirdly, it is printing the name of the file as what should be the first line read, which makes me think I've missed something very very simple here.
Console
run:
telnos.txt
null
loadData tested successfully
Please enter a name to look up: John
-1
Not found
BUILD SUCCESSFUL (total time: 6 seconds)
ArrayPhoneDirectory.java
import java.util.*;
import java.io.*;
public class ArrayPhoneDirectory implements PhoneDirectory {
private static final int INIT_CAPACITY = 100;
private int capacity = INIT_CAPACITY;
// holds telno of directory entries
private int size = 0;
// Array to contain directory entries
private DirectoryEntry[] theDirectory = new DirectoryEntry[capacity];
// Holds name of data file
private final String sourceName = "telnos.txt";
File telnos = new File(sourceName);
// Flag to indicate whether directory was modified since it was last loaded or saved
private boolean modified = false;
// add method stubs as specified in interface to compile
public void loadData(String sourceName) {
Scanner read = new Scanner("telnos.txt").useDelimiter("\\Z");
int i = 1;
String name = null;
String telno = null;
while (read.hasNextLine()) {
if (i % 2 != 0)
name = read.nextLine();
else
telno = read.nextLine();
add(name, telno);
i++;
}
}
public String lookUpEntry(String name) {
int i = find(name);
String a = null;
if (i >= 0) {
a = name + (" is at position " + i + " in the directory");
} else {
a = ("Not found");
}
return a;
}
public String addChangeEntry(String name, String telno) {
for (DirectoryEntry i : theDirectory) {
if (i.getName().equals(name)) {
i.setNumber(telno);
} else {
add(name, telno);
}
}
return null;
}
public String removeEntry(String name) {
for (DirectoryEntry i : theDirectory) {
if (i.getName().equals(name)) {
i.setName(null);
i.setNumber(null);
}
}
return null;
}
public void save() {
PrintWriter writer = null;
// writer = new PrintWriter(FileWriter(sourceName));
}
public String format() {
String a;
a = null;
for (DirectoryEntry i : theDirectory) {
String b;
b = i.getName() + "/n";
String c;
c = i.getNumber() + "/n";
a = a + b + c;
}
return a;
}
// add private methods
// Adds a new entry with the given name and telno to the array of
// directory entries
private void add(String name, String telno) {
System.out.println(name);
System.out.println(telno);
theDirectory[size] = new DirectoryEntry(name, telno);
size = size + 1;
}
// Searches the array of directory entries for a specific name
private int find(String name) {
int result = -1;
for (int count = 0; count < size; count++) {
if (theDirectory[count].getName().equals(name)) {
result = count;
}
System.out.println(result);
}
return result;
}
// Creates a new array of directory entries with twice the capacity
// of the previous one
private void reallocate() {
capacity = capacity * 2;
DirectoryEntry[] newDirectory = new DirectoryEntry[capacity];
System.arraycopy(theDirectory, 0, newDirectory,
0, theDirectory.length);
theDirectory = newDirectory;
}
}
ArrayPhoneDirectoryTester.java
import java.util.Scanner;
public class ArrayPhoneDirectoryTester {
public static void main(String[] args) {
//create a new ArrayPhoneDirectory
PhoneDirectory newTest = new ArrayPhoneDirectory();
newTest.loadData("telnos.txt");
System.out.println("loadData tested successfully");
System.out.print("Please enter a name to look up: ");
Scanner in = new Scanner(System.in);
String name = in.next();
String entryNo = newTest.lookUpEntry(name);
System.out.println(entryNo);
}
}
telnos.txt
John
123
Bill
23
Hello
23455
Frank
12345
Dkddd
31231
In your code:
Scanner read = new Scanner("telnos.txt");
Is not going to load file 'telnos.txt'. It is instead going to create a Scanner object that scans the String "telnos.txt".
To make the Scanner understand that it has to scan a file you have to either:
Scanner read = new Scanner(new File("telnos.txt"));
or create a File object and pass its path to the Scanner constructor.
In case you are getting "File not found" errors you need to check the current working directory. You could run the following lines and see if you are indeed in the right directory in which the file is:
String workingDir = System.getProperty("user.dir");
System.out.println("Current working directory : " + workingDir);
You need to also catch the FileNotFoundException in the function as follows:
public void loadData(String sourceName) {
try {
Scanner read = new Scanner(new File("telnos.txt")).useDelimiter("\\Z");
int i = 1;
String name = null;
String telno = null;
while (read.hasNextLine()) {
if (i % 2 != 0)
name = read.nextLine();
else {
telno = read.nextLine();
add(name, telno);
}
i++;
}
}catch(FileNotFoundException ex) {
System.out.println("File not found:"+ex.getMessage);
}
}
You are actually parsing the filename not the actual file contents.
Instead of:
new Scanner("telnos.txt")
you need
new Scanner( new File( "telnos.txt" ) )
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

Java FileNotFoundException error as statement not in a method

I have 2 files where 1(OrderCatalogue.java) reads in contents of a external file and 2(below). But I'm having the "FileNotFoundException must be caught or declard to be thrown" error for this line "OrderCatalogue catalogue= new OrderCatalogue();" and I understand that because its not in a method. But if i try puting it in a method, the code under the "getCodeIndex" and "checkOut" methods can't work with the error message of "package catalogue does not exist". Anyone has any idea how i can edit my code to make them work? Thank you!!
public class Shopping {
OrderCatalogue catalogue= new OrderCatalogue();
ArrayList<Integer> orderqty = new ArrayList<>(); //Create array to store user's input of quantity
ArrayList<String> ordercode = new ArrayList<>(); //Create array to store user's input of order number
public int getCodeIndex(String code)
{
int index = -1;
for (int i =0;i<catalogue.productList.size();i++)
{
if(catalogue.productList.get(i).code.equals(code))
{
index = i;
break;
}
}
return index;
}
public void checkout()
{
DecimalFormat df = new DecimalFormat("0.00");
System.out.println("Your order:");
for(int j=0;j<ordercode.size();j++)
{
String orderc = ordercode.get(j);
for (int i =0;i<catalogue.productList.size();i++)
{
if(catalogue.productList.get(i).code.equals(orderc))
{
System.out.print(orderqty.get(j)+" ");
System.out.print(catalogue.productList.get(i).desc);
System.out.print(" # $"+df.format(catalogue.productList.get(i).price));
}
}
}
}
And this is my OrderCatalogue file
public OrderCatalogue() throws FileNotFoundException
{
//Open the file "Catalog.txt"
FileReader fr = new FileReader("Catalog.txt");
Scanner file = new Scanner(fr);
while(file.hasNextLine())
{
//Read in the product details in the file
String data = file.nextLine();
String[] result = data.split("\\, ");
String code = result[0];
String desc = result[1];
String price = result[2];
String unit = result[3];
//Store the product details in a vector
Product a = new Product(desc, code, price, unit);
productList.add(a);
}
It seems the OrderCatalogue constructor throws FileNotFoundException. You can initialize catalogue inside Shopping constructor and catch the exception or declare it to throw FileNotFoundException.
public Shopping() throws FileNotFoundException
{
this.catalogue= new OrderCatalogue();
or
public Shopping()
{
try{
this.catalogue= new OrderCatalogue();
}catch(FileNotFoundException e)
blah blah
}

Employee Program. JAVA basics

I am writing a simple start-up java program. The problem I am facing is that the company name is not being added properly.
public class Company {
public static BufferedReader br;
public static BufferedReader br1;
public static String numberOfCompanies;
public static void main(String[] args) {
// TODO Auto-generated method stub
CompanyDetails qw = new CompanyDetails();
try{
//Scanner in = new Scanner(System.in);
br = new BufferedReader(new InputStreamReader(System.in));
br1 = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter number of companies: ");
numberOfCompanies = br.readLine();
int G = Integer.parseInt(numberOfCompanies);
for (int i = 1; i <= G; i++) {
qw = new CompanyDetails();
System.out.println("Enter name of the company: ");
String company = br1.readLine();
qw.company(company, i);
}
for (int i = 0; i <= G; i++) {
qw.companySummary(G);
}
} catch (IOException io) {
io.printStackTrace();
}
}
}
class CompanyDetails {
String company, name;
public String input;
public static BufferedReader br;
public double iE;
public static String numberOfCompanies;
String nameOfCompany;
String[] nameofCompany1 = new String[100];
int ir,i,employee;
ArrayList<String> bulk = new ArrayList<String>();
public String[] company(String input, int i) {
// TODO Auto-generated method stub
//ArrayList bulk = new ArrayList();
//for(int ith = i; ith<= 2; i++){
nameOfCompany = i+input;
bulk.add(nameOfCompany);
bulk.add(nameOfCompany);
// }
return nameofCompany1;
}
public void employee(double d) {
// TODO Auto-generated method stub
ir = (int)d;
}
public void companySummary(int G) {
System.out.println("Number of companies: " + G);
System.out.println("Name of company: " +bulk +" ");
System.out.println("Number of employees: "+ir);
}
}
The output I am getting is
Why aren't I getting 234 at the position 1 of the arraylist ??
You are creating a new CompanyDetails object in each iteration of the loop, there by loosing your earlier object:
for (int i = 1; i <= G; i++) {
qw = new CompanyDetails();
You are already creating an CompanyDetails object at the start of main method:
CompanyDetails qw = new CompanyDetails();
So you don't have to do it again in the for loop.
public String[] company(String input, int i) {
nameOfCompany = i+input;
bulk.add(nameOfCompany);
bulk.add(nameOfCompany); .// Why are you adding nameOfCompany twice .
return nameofCompany1; //Why are you returning nameofCompany1 which is null here
}
qw = new CompanyDetails(); //this line should be out of the loop.
Work on Naming Convention.
Please provide more details on what you want to do and what output you expect .
Take a look at code-snippet: qw = new CompanyDetails(); is instantiated per loop.
It should be:
qw = new CompanyDetails();
for (int i = 1; i <= G; i++) {
...
}
As #CodeBuzz pointed out : remove bulk.add(nameOfCompany); in company() method and also do not iterate the qw.companySummary(G); method.
In your CompanyDetails class remove one line bulk.add(nameOfCompany); in the method public String[] company(String input, int i) and put qw = new CompanyDetails(); outside of the for loop in you main method and it will work fine.
Main class
public class Company {
public static BufferedReader br;
public static BufferedReader br1;
public static String numberOfCompanies;
public static void main(String[] args) {
// TODO Auto-generated method stub
CompanyDetails qw = new CompanyDetails();
try{
//Scanner in = new Scanner(System.in);
br = new BufferedReader(new InputStreamReader(System.in));
br1 = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter number of companies: ");
numberOfCompanies = br.readLine();
int G = Integer.parseInt(numberOfCompanies);
qw = new CompanyDetails();
for (int i = 1; i <= G; i++) {
System.out.println("Enter name of the company: ");
String company = br1.readLine();
qw.company(company, i);
}
for (int i = 0; i <= G; i++) {
qw.companySummary(G);
}
} catch (IOException io) {
io.printStackTrace();
}
}
}
CompanyDetails class
class CompanyDetails {
String company, name;
public String input;
public static BufferedReader br;
public double iE;
public static String numberOfCompanies;
String nameOfCompany;
String[] nameofCompany1 = new String[100];
int ir,i,employee;
ArrayList<String> bulk = new ArrayList<String>();
public String[] company(String input, int i) {
// TODO Auto-generated method stub
//ArrayList bulk = new ArrayList();
//for(int ith = i; ith<= 2; i++){
nameOfCompany = i+input;
//bulk.add(nameOfCompany);
bulk.add(nameOfCompany);
// }
return nameofCompany1;
}
public void employee(double d) {
// TODO Auto-generated method stub
ir = (int)d;
}
public void companySummary(int G) {
System.out.println("Number of companies: " + G);
System.out.println("Name of company: " +bulk +" ");
System.out.println("Number of employees: "+ir);
}
}
I can see your question has been well answered. I have one little remark I would like to add related to naming conventions. I would rename method company in the CompanyDetails class to AddCompany or registerCompany to make sure your readers understand the meaning of that method without having to go deep into its implementation details.
Regards,
The program for retrieving Employee details is below:
package employee;
import java.util.*;
public class Employee
{
String name, gender,address;
int id;
float salary,da,hra,gross_pay;
public void getdata()
{
Scanner in= new Scanner(System.in);
System.out.println("Enter the name of employee");
name=in.next();
System.out.println("Enter the id of employee");
id=in.nextInt();
System.out.println("Enter the gender of employee");
gender=in.next();
System.out.println("Enter the address of employee");
address=in.next();
}
public void calc()
{
Scanner in= new Scanner (System.in);
System.out.println("enter the salary of employee");
salary=in.nextFloat();
da=salary*15/100;
hra=salary*10/100;
gross_pay=salary+da+hra;
}
public void display()
{
System.out.println("Employee Details");
System.out.println("Employee name:"+name+" ");
System.out.println("Employee id:"+id+" ");
System.out.println("Employee gender:"+gender+" ");
System.out.println("Employee address:"+address+" ");
System.out.println("Employee salary:"+salary+" ");
System.out.println("da amount"+da+" ");
System.out.println("hra amount:"+hra+" ");
System.out.println("Gross_pay of employee:"+gross_pay+" ");
}
public static void main(String[] args)
{
Employee emp=new Employee();
emp.getdata();
emp.calc();
emp.display();
}
}
Output:
Enter the name of employee
Raju
Enter the id of employee
20
Enter the gender of employee
Male
Enter the address of employee
XYZ Street, India.
Enter the salary of employee
45000
Employee Details
Employee name:Raju
Employee id:20
Employee gender:Male
Employee address:XYZ
Employee salary:45000.0
DA amount6750.0
HRA amount:4500.0
Gross_pay of employee:56250.0

Categories