Hello,

My prof asked me to write a program that takes some information and save them for further uses.
But I do not know how to save and keep information for a long time in java.

I think I have to use arrays, but I don't know what should I do exactly.

Please guide me in this way.

Recommended Answers

All 30 Replies

Anything(eg arrays) you create in your Java app is lost when the app terminates. To save data for later use you need to write it to a file or a database. Probably the easiest is to write in in text form (same as printing) to a text file. Google will give you lots of examples and explanations.

My program should take information of 100 employees and save them.
The prof said I should not use databases or text files to archive data.
I have no idea how could I save data of 100 persons without using DB ,etc

Are all disk files not allowed, or is it just files in text that are not allowed?

If you can use a disk file, look at serialization of a class object as way to save its contents. Fill an array in a class object and write it as an object to a file.

It sounds to me like he just wants you to save them in memory in an array.

All disk files not allowed

Are all disk files not allowed, or is it just files in text that are not allowed?

If you can use a disk file, look at serialization of a class object as way to save its contents. Fill an array in a class object and write it as an object to a file.

Is it possible to save 100 contacts in memory simultaneously in an array?

It sounds to me like he just wants you to save them in memory in an array.

Sure, you could probably have thousands without an issue. It depends on how much memory you allow the VM to take and the size of your objects, but 100 certainly won't be a problem.

save them for further uses.

How far in the future? Do you expect the data to be available after the computer is shutdown and restarted?

This code made me confused. Why I'm getting cannot find symbol error?

import java.util.Scanner;

abstract class Employee {
	int SSN[] = new int[100];
	String Fname[] = new String[100];
	String Lname[] = new String[100];
}

class SalariedEmployee extends Employee {
	int weeklySalary[] = new int[100];

	void getInfo() {
		Scanner s = new Scanner(System.in);
		for (int i=0; i<100; i++) {
			SSN[i] = s.nextInt();
			weeklySalary[i] = s.nextInt();
			Fname[i] = s.nextLine();
			Lname[i] = s.nextLine();
		}
	}
}

public class Main {
    public static void main (String[] args) {
             Employee ref;
             SalariedEmployee SE = new SalariedEmployee();
             ref = SE;
             ref.getInfo();
    }
}

You can see the exact error that I'm getting when running javac :

c:\java\my box\Main.java:46: cannot find symbol
symbol  : method getInfo()
location: class Employee
             ref.getInfo();
                ^
1 error

What class is getInfo() a method in?

The compiler does not think it is in the Employee class (ref is an Employee).

getInfo() method is in SalariedEmployee class.
I also tried SE.getInfo(); but got same error

I also tried SE.getInfo(); but got same error

Show the code and the errors for when you tried that

I'm not sure what the default method access is for getInfo(). Try adding public so it instead says: "public void getInfo() {".

Also, your getInfo method does not return anything, which is bad code for a method with get in its name. You should either return something or call it something else.

Fixed the problem by adding getInfo() method into super class "Employee"
but facing a new issue.
When running the program, one of string parameters (Lname and Fname) will jump and can not enter any value for it.
Run the program for better understanding of the issue:

import java.util.Scanner;

abstract class Employee {
	int SSN[] = new int[100];
	String Fname[] = new String[100];
	String Lname[] = new String[100];
	void getInfo() {
	}
}

class SalariedEmployee extends Employee {
	int weeklySalary[] = new int[100];

    void getInfo() {
		Scanner s = new Scanner(System.in);
		for (int i=0; i<100; i++) {
			System.out.println("Enter First Name: ");
			Fname[i] = s.nextLine();
			System.out.println("Enter Last Name: ");
			Lname[i] = s.nextLine();
			System.out.println("Enter SSN: ");
			SSN[i] = s.nextInt();
			System.out.println("Enter Weekly Salary: ");
			weeklySalary[i] = s.nextInt();
			break;
		}
	}
}

public class Main {
public static void main (String[] args) {
Employee ref;
SalariedEmployee SE = new SalariedEmployee();
ref = SE;
ref.getInfo();
}
}

When using the nextInt method you must call nextLine() to clear the Enter character that remains in Scanner's buffer.

What is the purpose of the break statement? The loop won't continue looping with that.

What is the purpose of the ref variable? Why not use SE directly?

May you explain with an example?

I'm using break statement to stop looping and return to command line
and also using ref variable because my prof said I have to use polymorphism. There are 3 other classes (other types of employees) that I need to add to the program. am I wrong?

Then why have the for loop if you break out the first time?

Your usage of ref looks weird/unusual. It looks like the code is being tested and will be changed to something else when you're done testing.

To see how nextLine and nextInt work, write a small test program that uses each of them several times in different order to see what happens.

Try entering more than one numeric value on one line before pressing Enter.

Change the program to have the calls to nextLine and nextInt in different order.
Print out what is read in by each.

R32@
This is just a question, because I don't know what you have or have not been taught yet, but did you consider an array of Employees, into which you can store instances of a SalariedEmployee or the other two subclasses?

Employee[] allEmployess = new Employee[100];
allEmployess[0] = new SalariedEmployee...

I'm asking because the way you have it now, with one big Employee class containing arrays for fName, lName etc isn't going to work well with polymorphism and subclasses.

Then why have the for loop if you break out the first time?

Your usage of ref looks weird/unusual. It looks like the code is being tested and will be changed to something else when you're done testing.

I need to archive 100 employees. I think I should use for loop to get information. Please tell me how do I get employee information if I'm wrong?

I'm new in java and OOP too and trying to use polymorphism in my project. Thaht's why I'm asking you to help me.

R32@
This is just a question, because I don't know what you have or have not been taught yet, but did you consider an array of Employees, into which you can store instances of a SalariedEmployee or the other two subclasses?

Employee[] allEmployess = new Employee[100];
allEmployess[0] = new SalariedEmployee...

I'm asking because the way you have it now, with one big Employee class containing arrays for fName, lName etc isn't going to work well with polymorphism and subclasses.

As I mentioned above, I'm new and do not know what should I do exactly.
I taught basics of java (arrays,...) and object oriented principles (e.g. overriding,overloading,super keyword,inheritance).
May you explain more about Employee array? Do you mean I need to use a unique array called Employee to and save each type of employees into that array?

Do you mean I need to use a unique array called Employee to and save each type of employees into that array?

That's how I would do it - define an Employee class that holds info for ONE employee, with similar subclasses, then put all the instances of any of those classes into a single array of Employee objects.

Thanks for your suggestion

My code is working but can not save information and search them.

Look at the following codes:
Problem is with methods getInfo and Search. Please help me to fix this issue.

import java.util.Scanner;

abstract class Employee {
	int SSN[] = new int[100];
	String Fname[] = new String[100];
	String Lname[] = new String[100];
	void getInfo() {
	}
	void Search() {
	}
} // End of Employee class

class SalariedEmployee extends Employee {
	int weeklySalary[] = new int[100];

    void getInfo() {
		Scanner s = new Scanner(System.in);
		for (int i=0; i<100; i++) {
			System.out.println("Enter First Name: ");
			Fname[i] = s.nextLine();
			System.out.println("Enter SSN: ");
			SSN[i] = s.nextInt();
			System.out.println("Enter Last Name: ");
			Lname[i] = s.nextLine();
			System.out.println("Enter Weekly Salary: ");
			weeklySalary[i] = s.nextInt();
			break;
		}
	}

	void Search() {
		int n=99;
		int desiredSSN;
		Scanner s = new Scanner(System.in);
		System.out.println ("Enter SSN to search: ");
		desiredSSN = s.nextInt();
		for (int i=n-100; i<n; i++) {
			if (SSN[i] == desiredSSN) {
				System.out.println ("Congratulations! Search was successful.");
				System.out.println ("*** Salaried Employee ***");
				System.out.println (Fname[i]);
				System.out.println ("Weekly Salary: " + weeklySalary[i]);
			}
			else {System.out.println ("SSN not found");}
        }
	}

} // End of SalariedEmployee class

class ShowMenu {
      int Option;
    void Menu () {
        System.out.println ("\n Welcome back to admin area. Please choose an option \n");
        System.out.println ("----------------------------------------------------------------------------");
        System.out.println ("|  1. Add Salaried Employee        |  2. Add Hourly Employee               |");
        System.out.println ("----------------------------------------------------------------------------");
        System.out.println ("|  3. Add Commission Employee      |  4. Add Commission+Salaried Employee  |");
        System.out.println ("----------------------------------------------------------------------------");
        System.out.println ("|  5. Search for an Employee       |  6. Edit an existing employee         |");
        System.out.println ("----------------------------------------------------------------------------");
        System.out.println ("|  7. Remove an existing employee  |  8. Exit                              |");
        System.out.println ("----------------------------------------------------------------------------");
        System.out.println (" ");
        System.out.println ("Enter a number:");
        Scanner s = new Scanner(System.in);
        Option = s.nextInt();
        if (Option<1 || Option>8) {
        System.out.println ("The Number Must Be Between 1 and 8");
        System.out.println ("Enter Another Number:");
        Option = s.nextInt();
        }
    }
} // End of MainPage class



public class Menu {
    public static void main (String[] args) {
             String user = "admin";
             int pass = 123;
             int p;
             String u;
             int empType;

        Employee ref;
        SalariedEmployee SE = new SalariedEmployee();
        ShowMenu mn = new ShowMenu();

    	Scanner s = new Scanner(System.in);
            System.out.println ("Enter Username:");
    	 u = s.nextLine();
    	 if (u.equals(user)) {
    	  	System.out.println ("Enter Password:");
    	 	p = s.nextInt();
      	  	if (p == pass) {
                mn.Menu(); //Show Menu
                if (mn.Option == 1) {
                    System.out.println("Add a Salaried Employee");
                    ref = SE;
                    ref.getInfo();
                    System.out.println ("Employee has been successfully added. \n");
                    System.out.println ("Returning to Main Menu ...");
                    mn.Menu();
                }
                if (mn.Option == 5) {
                	System.out.println ("\n Choose employee type:");
                    System.out.println ("1. Salaried Employee");
                    System.out.println ("2. Hourly Salaried Employee");
                    System.out.println ("3. Commission Employee");
                    System.out.println ("4. Commission + Salaried Employee \n");
                    empType = s.nextInt();
                    if (empType == 1)
                    	SE.Search();
                }
                if (mn.Option == 8)
                	System.out.println ("\n Good Bye !");

         } else {
    	 	    System.out.println ("Incorrect Password");
    	 	}

    	 } else {
    	  	System.out.println ("Invalid User");
    	 }
    }

}

If you are getting execution errors please copy and paste the full text here.

If you are getting execution errors please copy and paste the full text here.

C:\java\my box\>java Menu
Enter Username:
admin
Enter Password:
123

 Welcome back to admin area. Please choose an option

----------------------------------------------------------------------------
|  1. Add Salaried Employee        |  2. Add Hourly Employee               |
----------------------------------------------------------------------------
|  3. Add Commission Employee      |  4. Add Commission+Salaried Employee  |
----------------------------------------------------------------------------
|  5. Search for an Employee       |  6. Edit an existing employee         |
----------------------------------------------------------------------------
|  7. Remove an existing employee  |  8. Exit                              |
----------------------------------------------------------------------------

Enter a number:
1
Add a Salaried Employee
Enter First Name:
John
Enter SSN:
2
Enter Last Name:  <--- JUMPED!
Enter Weekly Salary:
1000
Employee has been successfully added.

Returning to Main Menu ...

 Welcome back to admin area. Please choose an option

----------------------------------------------------------------------------
|  1. Add Salaried Employee        |  2. Add Hourly Employee               |
----------------------------------------------------------------------------
|  3. Add Commission Employee      |  4. Add Commission+Salaried Employee  |
----------------------------------------------------------------------------
|  5. Search for an Employee       |  6. Edit an existing employee         |
----------------------------------------------------------------------------
|  7. Remove an existing employee  |  8. Exit                              |
----------------------------------------------------------------------------

Enter a number:
5

 Choose employee type:
1. Salaried Employee
2. Hourly Salaried Employee
3. Commission Employee
4. Commission + Salaried Employee

1
Enter SSN to search:
2
[I]Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
        at SalariedEmployee.Search(Menu.java:46)
        at Menu.main(Menu.java:121)[/I]
System.out.println("Enter SSN: ");
SSN[i] = s.nextInt();
System.out.println("Enter Last Name: ");
Lname[i] = s.nextLine();

Enter Last Name: <--- JUMPED!

when you inputted the number, you’re unintentionally leaving a trailing a newline behind. The newline you left there is then captured instantly upon reaching the next s.nextLine()
read here for more info:
input skipping in java

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at SalariedEmployee.Search(Menu.java:46)
at Menu.main(Menu.java:121)

At the search method line 32-37

n=99;
// ...
for (int i=n-100; i<n; i++) { // you initialized that i = -1

It's pretty obvious what happened here

Thank you so much for your helps

I have another problem with my program. when I enter a number like 0.1 or 0.2 ,... for an input, the following error occurs:

Enter Commission Rate:
0.1
Exception in thread "main" java.util.InputMismatchException
        at java.util.Scanner.throwFor(Unknown Source)
        at java.util.Scanner.next(Unknown Source)
        at java.util.Scanner.nextInt(Unknown Source)
        at java.util.Scanner.nextInt(Unknown Source)
        at CommissionEmployee.setInfo(Menu.java:151)
        at Menu.main(Menu.java:348)

Related command is as bellow:

System.out.println("\n Enter Commission Rate:");
			commissionRate[i] = s.nextInt();

Am I doing something wrong?

Note: commissionRate has been initialized as double.

java.util.InputMismatchException
nextInt
when I enter a number like 0.1 or 0.2

Those numbers are not integers.

Look at the Scanner class and find a method that will work with those inputs.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.