How do I get my java ArrayList to display properly? - java

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));
}
}

Related

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();
}
}
}

Java Scanner Taking Extra Input

I'm working on a switch statement that takes inputs with Scanner, and when I run in NetBeans, one of the inputs takes an extra blank input. The extra input happens at variable dateAdmission when the user is asked to input "Enter date of admission".
case "patient":
{
System.out.println("Enter name: ");
String name = in.nextLine();
System.out.println("Enter Address: ");
String address = in.nextLine();
System.out.println("Enter date of birth: ");
String dob = in.nextLine();
System.out.println("Enter MCP number: ");
int mcp = in.nextInt();
in.nextLine();
System.out.println("Enter date of admission: ");
String dateAdmission = in.nextLine();
System.out.println();
String hospital = in.nextLine();
System.out.println("Enter name of doctor: ");
String doctor = in.nextLine();
System.out.println("Enter room number: ");
int roomNum = in.nextInt();
a[i] = new Patient(name, address, dob, mcp, dateAdmission, hospital, doctor, roomNum);
break;
}
You might have forgotten to provide System.out.println("Enter hospital");
before the
String hospital = in.nextLine();
What happened was it printed nothing and took the extra input for hospital?

Repeat user inputs while adding it to an array list

I’m trying to ask the user if they want to add another person to array list, "list". My thought was to loop to ask, then add those inputs into an array, "inf" and then put that array within an array list. Right now when I repeat the code it just erases the previous inputs; how would I make it so it adds to the array list after each iteration?
public class test {
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(System.in);
String ask = "no";
do {
System.out.println("Add? (yes/no)");
ask = scan.nextLine();
if (ask.equals("yes")){
//gather user info
System.out.println("Last Name: ");
String LastN = scan.nextLine();
System.out.println("First Name: ");
String FirstN = scan.nextLine();
System.out.println("# of Children:");
String Children = scan.nextLine();
System.out.println("Address:");
String Adr = scan.nextLine();
System.out.println("Phone #:");
String Pho = scan.nextLine();
Date dategather = new Date();
String Date = String.format("%tD", dategather);
//Input the data into an array
String[] inf = {LastN,FirstN,Children,Adr,Date,Pho};
ArrayList<String> list = new ArrayList<String>();
Collections.addAll(list,inf);
System.out.println(list);
}
} while (ask.equals("yes"));
}
}
You'd want to declare the list outside the do-while structure, and if you want to print each line entry - then you do that right at the end of the do-while structure:
//here you declare the list OUTSIDE:
ArrayList<String> list = new ArrayList<String>();
do {
System.out.println("Add? (yes/no)");
ask = scan.nextLine();
if (ask.equals("yes")){
//gather user info
System.out.println("Last Name: ");
String LastN = scan.nextLine();
System.out.println("First Name: ");
String FirstN = scan.nextLine();
System.out.println("# of Children:");
String Children = scan.nextLine();
System.out.println("Address:");
String Adr = scan.nextLine();
System.out.println("Phone #:");
String Pho = scan.nextLine();
Date dategather = new Date();
String Date = String.format("%tD", dategather);
//Input the data into an array
String[] inf = {LastN,FirstN,Children,Adr,Date,Pho};
Collections.addAll(list,inf);
//so here you want to display what the person just entered:
System.out.println("You Have Entered : \n Last Name: "+LastN+" First Name: "+FirstN+" Children : "+Children+" Address: "+Adr+" Date of Birth: "+Date+" Phone Number: "+Pho);
}
} while (ask.equals("yes"));
I hope this helps you. Please give it a try and let me know.
You can create a class Person which has all the details of each person and add them to an ArrayList. Something like that:
(tip: you could make #children as integer instead of String)
public class test
{
public static void main(String[] args) throws FileNotFoundException {
ArrayList<Person> list = new ArrayList<Person>();
do
{
System.out.println("Add? (yes/no)");
ask = scan.nextLine();
if (ask.equals("yes")){
System.out.println("Last Name: ");
String lastName= scan.nextLine();
System.out.println("First Name: ");
String firstName= scan.nextLine();
System.out.println("# of Children:");
String children = scan.nextLine();
System.out.println("Address:");
String address= scan.nextLine();
System.out.println("Phone #:");
String phone= scan.nextLine();
Date dategather = new Date();
String date = String.format("%tD", dategather);
list.add(new Person(lastName, firstName, children,address, phone,date));
}
}while (ask.equals("yes"));
}
}
public class Person
{
String lastName, firstName, children,address, phone,date
public Person(String lastName,String firsName,String children,String address,String phone, String date)
{
this.lastName=lastName;
this.firsName=firsName;
this.children=children;
this.address=address;
this.phone=phone;
this.date=date;
}
}
In your code in every loop the arrayList is reseting as you reinitialize every time.

How to do the same thing with Array and ArrayList?

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.

How to read multi-word input into one String?

How do I read user inputs, one line at a time to create an object. Which then goes into a ArrayList? As you can see, when I enter the name, it's breaks it up and only stores the last name. Or if I do: first-middle-last name, it stores the middle and last name.
I enter the name the first time, which calls the search method first, to see if the name already exists in the ArrayList. That works fine. And if the name isn't in the list, the search returns null. Which then prompts the inputs and add method.
case 1: {
System.out.print("Enter the Students name: ");
String nameSearch = kbd.next();
Student stu = dc.search(nameSearch );
if (stu != null) {
System.out.println(stu);
}
else {
System.out.print("Enter name AGAIN: ");
String nameAdd= kbd.nextLine();
System.out.print("Enter grade (freshman, sophomore, junior, senior: ");
String categoryAdd = kbd.nextLine();
System.out.print("Major: ");
String majorAdd = kbd.nextLine();
System.out.print("Enter graduating year: ");
int yearAdd = kbd.nextInt();
System.out.print("Enter student ID: (xxxx.xxxx: ");
double idAdd= kbd.nextDouble();
dc.add(nameAdd, categoryAdd , majorAdd ,
yearAdd , idAdd);
}
break;
}
My input:
Enter the Students name: John Smith
Not Found(Search Method)
TEST
Enter name AGAIN: TEST2
Enter grade (freshman, sophomore, junior, senior: senior
Major: Computer Science
Enter graduating year: 2013
Enter student ID: 1234.4567
How it's stored inside the object when I print ArrayList:
Name: Smith
Grade: senior
Major: Computer Science
Graduating Year: 2013
Student ID: 1234.4567
The add method:
public Student add(String name, String grade,
String major, int year, double id) {
Student newStu = new Student(addName, addGrade, addMajor, addYear, addId);
studentList.add(newStu );
System.out.println("Added!");
return null;
}
This line:
String nameSearch = kbd.next();
Should probably be
String nameSearch = kbd.nextLine();
right?
Make kbd a BufferedReader (e.g. BufferedReader kbd = new BufferedReader(new InputStreamReader(System.in));), then do this...
case 1: {
System.out.print("Enter the Students name: ");
String nameSearch = kbd.readLine();
Student stu = dc.search(nameSearch );
if (stu != null) {
System.out.println(stu);
}
else {
System.out.print("Enter name AGAIN: ");
String nameAdd= kbd.readLine();
System.out.print("Enter grade (freshman, sophomore, junior, senior: ");
String categoryAdd = kbd.readLine();
System.out.print("Major: ");
String majorAdd = kbd.readLine();
System.out.print("Enter graduating year: ");
int yearAdd = Integer.parseInt(kbd.readLine());
System.out.print("Enter student ID: (xxxx.xxxx: ");
double idAdd= Double.parseDouble(kbd.readLine());
dc.add(nameAdd, categoryAdd , majorAdd ,
yearAdd , idAdd);
}
break;
}
It should be String nameSearch = kbd.nextLine();. I read on the multiline java tutorial.
Hope this helps. In some way.

Categories

Resources