How to do the same thing with Array and ArrayList? - java

So, I have an OOP course and my assignment was to make an abstract employee class and than make further base classes for it. This part was easy and after that I had to make an array of objects of 'Employee' type and use the whole polymorphism thing to initiate all the base classes accordingly.
This is the code I wrote in my main:
Scanner input = new Scanner (System.in);
int Size;
System.out.println("Enter Array Size");
Size = input.nextInt();
Employee [] Array = new Employee [Size];
int i;
int A;
System.out.println("Key: ");
System.out.println("Press 1 for Salaried Employee.");
System.out.println("Press 2 for Hourly Employee.");
System.out.println("Press 3 for Commision Employee.");
System.out.println("Press 4 for Base Plus Commision Employee.");
String Name;
String SSN;
double wage;
double hours;
double salary;
int Sales;
double CRate;
double BaseSalary;
for (i = 0; i < Array.length; i++ ) {
A = input.nextInt();
if (A == 1) {
do {
System.out.println("Enter Name");
input.nextLine();
Name = input.nextLine();
} while (Name == "");
do {
System.out.println("Enter Social Security Number");
SSN = input.nextLine();
} while (SSN == "");
Array [i] = new Salaried_Employee(Name, SSN);
System.out.println("Initial Earnings!" +Array[i].Earnings());
}
if (A == 2) {
do {
System.out.println("Enter Name");
input.nextLine();
Name = input.nextLine();
} while (Name == "");
do {
System.out.println("Enter Social Security Number");
SSN = input.nextLine();
} while (SSN == "");
System.out.println("Enter Wage!");
wage = input.nextDouble();
System.out.println("Enter hours!");
hours = input.nextDouble();
Array [i] = new Hourly_Employee (Name, SSN, wage, hours);
}
if (A == 3) {
do {
System.out.println("Enter Name");
input.nextLine();
Name = input.nextLine();
} while (Name == "");
do {
System.out.println("Enter Social Security Number");
SSN = input.nextLine();
} while (SSN == "");
System.out.println("Enter Sales!");
Sales = input.nextInt();
System.out.println("Enter Commision Rate!");
CRate = input.nextDouble();
Array [i] = new Comission_Employee (Name, SSN, Sales, CRate);
}
if (A == 4) {
do {
System.out.println("Enter Name");
input.nextLine();
Name = input.nextLine();
} while (Name == "");
do {
System.out.println("Enter Social Security Number");
SSN = input.nextLine();
} while (SSN == "");
System.out.println("Enter Sales!");
Sales = input.nextInt();
System.out.println("Enter Commision Rate!");
CRate = input.nextDouble();
System.out.println("Define the base salary");
BaseSalary = input.nextDouble();
Array [i] = new BassPlus_CommEmployee (Name, SSN, Sales, CRate, BaseSalary);
}
}
Now I have to do the exact same thing through Array List. I have googled the life out of this issue but I do not get how I can make an ArrayList that is of Employee type.
Please, Help!!

List<Employee> employeeList = new ArrayList<Employee>();
EDIT:
employeeList.add(new BassPlus_CommEmployee (Name, SSN, Sales, CRate, BaseSalary));
employeeList.add(new Hourly_Employee (Name, SSN, wage, hours));
etc.
I assume Employee is the Superclass. Well I think it is since you are using this exact snippet in your code.

ArrayList is an Object that contains other Object.
So you'll have to call methods to replace the assignement you did with Array.
array[i] = new Employee(); can be transposed to arraylist.add(new Employee()) for example
Then you'll need to find how to get the value to transpose Employee e = array[i]
Don't forget not to work with a null ArrayList.

Related

i need help in storing multiple user input into an array with maximum limitation and being able to call it later in the code

Im still learning java and i want to understand more about array. Im still in school and we were asked to create an asean phonebook which can store, edit, delete, and view/search the information that are inputted. Im still doing the storing of information block of code and im struggling how to save multiple input in an array that is limited only to 100 contacts and can be searched later in the code. Can someone help me with my task and make me understand??
import java.util.Scanner;
public class Phonebook
{
public static void main (String [] args)
{
Scanner input = new Scanner (System.in);
int i = 0;
String studentNumber, surName, firstName, occuPation, countryCode, areaCode, numBer;
char genDer;
do
{
Menu();
System.out.println(" ");
System.out.print("Go to: ");
String choice = input.next();
if (choice.equals("1") || choice.equals("2") || choice.equals("3") || choice.equals("4") || choice.equals("5"))
{
i++;
switch(choice)
{
case "1":System.out.println("Enter student number: ");
studentNumber = input.next();
System.out.println("Enter surname: ");
surName = input.next();
System.out.println("Enter first name: ");
firstName = input.next();
System.out.println("Enter occupation: ");
occuPation = input.next();
System.out.println("Enter gender (M for male, F for female): ");
genDer = input.next();
System.out.println("Enter counter code: ");
countryCode = input.next();
System.out.println("Enter area code: ");
areaCode = input.next();
System.out.println("Enter number: ");
numBer = input.next();
break;
case "2":System.out.println("2");break;
case "3":System.out.println("3");break;
case "4":System.out.println("4");break;
case "5":System.out.println("5");break;
}
}
else
{
System.out.println("Invalid keyword, Please try again");
}
}
while (i < 1);
}
static void Menu()
{
System.out.println("[1] Store to ASEAN phonebook");
System.out.println("[2] Edit entry in ASEAN phonebook");
System.out.println("[3] Delete entry from ASEAN phonebook");
System.out.println("[4] View\\search ASEAN phonebook");
System.out.println("[5] Exit");
}
}

Hi, the requirement is to display the user input in table format

The requirement is to display the user input student details in table format.
For example:
Enter the number of students
2
Enter the student1 details
28
Science
Is the student from same country[Y/N]
N
Enter the country
Australia
Enter the Student2 details
29
Commerce
Is the Student from same country[Y/N]
Y
The student details are
Age Subject Country
28 Science Australia
29 Commerce UK
**If the student are from same country by default the value would be printed as UK under country column.
I am stuck at the point where the value needs to be displayed in tabular format under headers(Age,name,country)along with the default value(UK in this case).
I am very new to java and not able to proceed furthur. Your any help would of great benefit to me.
Thanks in advance.
My Code is:
public class StudentTable{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
//Port obj = new Port();
int a,i;
String b = null;
System.out.println("Enter the number of students");
a = sc.nextInt();
int[] age = new int[a+1];
String[] name = new String[a+1];
for(i=1;i<a+1;i++){
System.out.println("Enter the students "+i+ " details");
age[i] = sc.nextInt();
sc.nextLine();
name[i] = sc.nextLine();
System.out.println("Is the student from same country[Y/N]");
b = sc.nextLine();
if(b=="N"){
System.out.println("Enter the country");
String country = sc.next();
return;
}
}
if(b=="Y");
String country = "India";
System.out.println("The student details are");
System.out.format("%-15s%-15s%-15s","Age","name","country");
1.Read about difference between "==" OR "equals",sysout.printf and clean code.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//Port obj = new Port();
int count, i;
String b ;
System.out.println("Enter the number of students");
count= sc.nextInt();
int[] age = new int[count];
String[] name = new String[count];
String[] country=new String[count];
for (i = 0; i < count; i++) {
System.out.println("Enter the students " + i+1 + " details");
System.out.println("Your age?");
age[i] = sc.nextInt();
sc.nextLine();
System.out.println("Your name?");
name[i] = sc.nextLine();
System.out.println("Is the student from same country[Y/N]");
b = sc.nextLine();
// if(b=="N")
if (b.equals("N")) {
System.out.println("Enter the country");
country[i] = sc.next();
}
//if(b=="Y")
if (b.equals("Y")) {
country[i] = "India";
}
}
String frmt= String.format("%-15s%-15s%-15s","Age","name","country");
System.out.println("The student details are");
System.out.println(frmt);
for( i=0;i<age.length;i++){
System.out.printf("%d %15s %14s",age[i],name[i],country[i]);
System.out.println();
}
}
}

How to create items for ArrayList based on user input

I'm making an inventory program for my class. I have an Item class, Inventory class with an ArrayList, and an Inventory tester class. I want to ask the user how many items they want to add to inventory and then add those items based on their parameters. This is what I have but it isn't working:
import java.util.Scanner;
public class InventoryTester
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Inventory myInventory = new Inventory();
System.out.println("Enter 1 to print all inventory data");
System.out.println("Enter 2 to add items to the inventory");
System.out.println("Enter 3 to ");
System.out.println("Enter 4 to ");
int choice = input.nextInt();
if (choice == 1)
{
myInventory.printAllData();
}
else if (choice == 2)
{
System.out.println("How many items are you adding?");
int numOfItemsToAdd = input.nextInt();
for (int i = 0; i < numOfItemsToAdd; i++)
{
System.out.println("Enter the name of item " + i);
input.nextLine();
String tempName = input.nextLine();
System.out.println("Enter the type of item " + i);
String tempType = input.nextLine();
System.out.println("Enter the price of item " + i);
double tempPrice = input.nextInt();
Item newItem = new Item(tempName, tempType, tempPrice);
myInventory.addItem(newItem);
}
}
input.close();
}
}
EDIT: What I thought my problem was, wasn't actually my problem. I got this piece working.
If you are using nextInt() and nextLine() together, you need to consume the last new line character before calling nextLine(). So you need to add an extra .nextLine() before your for loop like so:
int numOfItemsToAdd = input.nextInt();
input.nextLine(); //ADDED CODE
for (int i = 0; i <= numOfItemsToAdd; i++)
{
System.out.println("Enter the name of item " + i + 1);
String tempName = input.nextLine();
System.out.println("Enter the type of item " + i + 1);
String tempType = input.nextLine();
System.out.println("Enter the price of item " + i + 1);
double tempPrice = input.nextInt();
Item newItem = new Item(tempName, tempType, tempPrice);
myInventory.addItem(newItem);
}

How do I get my java ArrayList to display properly?

I have a class where a user inputs information about an employee (first and last name, address, hire date) for a user determined number of employees.
import java.util.ArrayList;
import java.util.Scanner;
public class Employee {
public static void main(String [] args){
String employeeName = null;
String employeeAddress = null;
String hireDate = null;
Scanner userInput = new Scanner(System.in);
System.out.println("How many employees would you like to enter information for?");
int numEmployees = userInput.nextInt();
for( int i = 0; i < numEmployees; i++) {
Scanner input = new Scanner(System.in);
System.out.println("Enter employees first name: ");
String firstName = input.nextLine();
System.out.println("Enter employees last name: ");
String lastName = input.nextLine();
System.out.println("Enter street employee lives on:");
String street = input.nextLine();
System.out.println("Enter city employee lives in:");
String city = input.nextLine();
System.out.println("Enter state employee lives in:");
String state = input.nextLine();
System.out.println("Enter employee's zip code:");
String zip = input.nextLine();
System.out.println("Enter month employee was hired:");
String month = input.nextLine();
System.out.println("Enter day employee was hired:");
String day = input.nextLine();
System.out.println("Enter year employee was hired:");
String year = input.nextLine();
Name name = new Name(firstName, lastName);
Address address = new Address(street, city, state, zip);
Date date = new Date(month, day, year);
employeeName = name.getName();
employeeAddress = address.getAddress();
hireDate = date.getDate();
ArrayList<String> obj = new ArrayList<String>();
obj.add(employeeName);
obj.add(employeeAddress);
obj.add(hireDate);
System.out.println(obj);
}
}
}
I'm trying to get the program to go through the user prompts, take that info and put it in a position in an ArrayList, then repeat for however many times the user determined earlier and display all at once at the end. Something like this:
FirstName LastName, Address, Hire Date
FirstName LastName, Address, Hire Date
And so on. Right now, my code will run through the user prompts, display that, then run through the next round of prompts and display that:
Enter Name:
Name
Enter Address:
Address
Enter Hire Date:
Hire Date
[Name, Address, Hire Date]
Enter Name:
Name
Enter Address:
Address
Enter Hire Date:
Hire Date
[Name, Address, Hire Date]
I realize this is because my array and array display are within the for loop, but when I move the array outside the loop I get no display. When I move just the array display outside the loop, my code doesn't compile.
Move this line:
System.out.println(obj);
out of the for loop. And use List to contain the ArrayList. Then you display it in a separate for loop:
List<ArrayList<String>> objs = new ArrayList<ArrayList<String>>(); //use list of objs
for( int i = 0; i < numEmployees; i++ )
{
//all the inputs
ArrayList<String> obj = new ArrayList<String>();
obj.add(employeeName);
obj.add(employeeAddress);
obj.add(hireDate);
objs.add(obj);
}
for( int i = 0; i < numEmployees; i++ ) //for loop just to display
System.out.println(objs.get(i)); //display each element here
What you are printing out is a tuple of type [string, string, string]. This can be represented as a List. Then for each employee you want to store this tuple in another List of type List<List<String>>.
public static void main( String [] args )
{
String employeeName = null;
String employeeAddress = null;
String hireDate = null;
Scanner userInput = new Scanner(System.in);
System.out.println("How many employees would you like to enter information for?");
int numEmployees = userInput.nextInt();
List<List<String>> employesInfo = new ArrayList<List<String>>();
for( int i = 0; i < numEmployees; i++ )
{
Scanner input = new Scanner(System.in);
System.out.println("Enter employees first name: ");
String firstName = input.nextLine();
System.out.println("Enter employees last name: ");
String lastName = input.nextLine();
System.out.println("Enter street employee lives on:");
String street = input.nextLine();
System.out.println("Enter city employee lives in:");
String city = input.nextLine();
System.out.println("Enter state employee lives in:");
String state = input.nextLine();
System.out.println("Enter employee's zip code:");
String zip = input.nextLine();
System.out.println("Enter month employee was hired:");
String month = input.nextLine();
System.out.println("Enter day employee was hired:");
String day = input.nextLine();
System.out.println("Enter year employee was hired:");
String year = input.nextLine();
Name name = new Name(firstName, lastName);
Address address = new Address(street, city, state, zip);
Date date = new Date(month, day, year);
employeeName = name.getName();
employeeAddress = address.getAddress();
hireDate = date.getDate();
ArrayList<String> obj = new ArrayList<String>();
obj.add(employeeName);
obj.add(employeeAddress);
obj.add(hireDate);
employeesInfo.add(obj);
}
for (int i = 0; i < numEmployees; i++ ) {
System.out.println(emploeesInfo.get(i));
}
}

How should I add a search method in this code

Scanner scanner = new Scanner(System.in);
int weight;
int age;
//arrays
List<String> last = new ArrayList<String>();
List<Integer> zage = new ArrayList<Integer>();
List<Integer> zweight = new ArrayList<Integer>();
int i = 0;
int userInput = 0;
//menu options
while(userInput != 2) {
userInput = scanner.nextInt(); // collects the user inputs
//several switch statements to answer each menu options
switch(userInput) {
case 1:
it saves and stores all the user inputs.
System.out.println("Enter a last name, age, weight"); //stores all the user information
String lastName = scanner.next();
last.add(lastName);
age = scanner.nextInt();
zage.add(age);
weight = scanner.nextInt();
zweight.add(weight);
break;
Need to add a search code where it will retrieve the user inputs and display it, but i'm not sure on how to do it.
case 5:
System.out.println("Enter the name; Enter DONE to exit");
System.out.println("FOUND!!! Last Name: " +last+ " Age: " +zage+ " Weight: " +zweight);
Your names are stored in a list so you can try this:
if (last.contains(searchName)) {
String foundName = last.get(last.indexOf(searchName));
System.out.println("FOUND!!! Last Name: " +foundName);
} else{
System.out.println("Last Name: " +searchName+ " NOT FOUND!!! ");
}
Note that duplicate names may be in the list so you may want to loop over the indexes.
you can do this:
String enteredLastName = scanner.next();
for (String name : last){
if (name.equals(enteredLastName ){
//do something
}
}

Categories

Resources