how to store information using array list - java

This my code, I just print screen it because I'm getting an error while posting this code
how to make this program to store personal information and store another person information.

Instead of making a do-while, then you could write a separate method for it and call it when needed
public void gatherUserInformation()
{
System.out.println("Enter name:");
...
System.out.println("Enter last name ");
...
}
Then call this method from your main method, and then make the first person print out.
Then in your main method, make this right after:
if(scan.nextInt() == 1)
{
gatherUserInformation()
}

You can create Person class like:
public class Person{
private String name;
private String lastname;
// void cons
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public String getLastname(){
return lastname;
}
public void setLastname(String lastname){
this.lastname= lastname;
}
}
And after that you change our main to work with that:
ArrayList<Person> pList = new ArrayList<>();
At the beginning of each loop:
Person person = new Person(); // void cons
And after that you can add 'person' in pList, use get methods to get object values and set methods to change that values:
person.setName(scan.next());
To show person name:
person.getName();
To show pList, open another loop:
int i = 1;
for ( Person p : pList ){
System.out.println("Person " + i + " name: " + p.getName());
System.out.println("Person " + i + " lastname: " + p.getLastname());
System.out,println(" ----------------------------------------- ");
i++;
}
I do not test but I think that's it
Good Lucky

Related

Mooc Helsinki Part 1 Week 4 Exercise 18 Java Weird Occurrence

Having a problem here with this error which the solution to is simply beyond me.
FAIL: PersonalInformationCollectionTest testInputFirst
Something weird occurred. It could be that the void main (String[] args) method of the class class PersonalInformationCollection has disappeared or your program crashed due to an exception. More information: java.util.NoSuchElementException.
It then says the same thing but for testInputSecond as well.
Can't find any reason for whats wrong. Looked online at a correct solution and perhaps it's just my poor eye sight but i couldn't see a single difference between my somehow incorrect code and their correct code.
Thanks for any help in advance.
import java.util.ArrayList;
import java.util.Scanner;
public class PersonalInformationCollection {
public static void main(String[] args) {
// implement here your program that uses the PersonalInformation class
ArrayList<PersonalInformation> infoCollection = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("First name: ");
String firstName = scanner.next();
if (firstName.isEmpty()){
break;
}
System.out.println("Last name: ");
String lastName = scanner.next();
System.out.println("Identification number: ");
String idNumber = scanner.next();
infoCollection.add(new PersonalInformation(firstName, lastName, idNumber));
}
for (PersonalInformation personalInfo : infoCollection){
System.out.println(personalInfo.getFirstName() + " " + personalInfo.getLastName());
}
}
}
Solved by using scanner.nextLine() rather than scanner.next(). No idea how that made such a difference in this case
Use the more general type for your variables as you can, because it doesn't change the logic if you would use an LinkedList instaed of an Arraylist and also it has the same methods you are using.
For strings use scanner,nextLine()
numberId or simply id should be a number integer would be great so use scanner.nextInt() to get only integer in here
implement/override the toString methode in your class PersonalInformation to have the string reprensetation at one point
class PersonalInformation
public class PersonalInformation {
private final int id;
private final String firstName;
private final String lastName;
public PersonalInformation(int id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
private int getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
#Override
public String toString() {
return "PersonalInformation{" +
"id=" + id +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
'}';
}
}
class PersonalInformationCollection
public static class PersonalInformationCollection {
public static void main(String[] args) {
// implement here your program that uses the PersonalInformation class
List<PersonalInformation> infoCollection = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("Identification number: ");
int id = scanner.nextInt();
if (id < 0){
break;
}
System.out.print("First name: ");
String firstName = scanner.nextLine();
System.out.print("Last name: ");
String lastName = scanner.next();
infoCollection.add(new PersonalInformation(id, firstName, lastName));
}
for (PersonalInformation personalInfo : infoCollection){
System.out.println(personalInfo);
}
scanner.close();
}
}

I want to add to an arrayList through user input

I have been trying to create a small program that prompts the user for input that takes an employee name and salary adds it to an arrayList, then displays options on the screen(e.g 0: quit, 1: add, 2: display), reads the input then proceeds based on the input.Displaying would just be(e.g Last Name: Smith Salary: £14000. Just need some help to point me in the right direction. I currently have 3 classes Employee, Employee List and Employee Test.
This class prompts the user input.
import java.util.Scanner;
public class Employee {
private String Last_Name;
private int Salary;
public Employee(){
Scanner inputValues = new Scanner(System.in);
System.out.print("Enter employee last name: ");
Last_Name = inputValues.next();
System.out.print("Enter Employee Salary: " + "£");
Salary = inputValues.nextInt();
}
public void Display(){
System.out.printf("Name: " + Last_Name + " " + "Salary: " + Salary);
System.out.println("\n");
}
}
This class is supposed to be adding the employees to an arraylist but im not sure if im doing it correctly.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class EmployeeList extends Employee{
private List <Employee> employee = new ArrayList<Employee>();
public EmployeeList(Employee person) {
employee.add(person);
}
public void DisplayEmployees(){
System.out.println("Employee:" + employee.size());
displayList(employee);
}
public static void displayList(List employee) {
}
}
This is where the main method is
import java.util.Scanner;
public class EmployeeTest {
public static void main(String[] args) {
Employee employee = new Employee();
employee.Display();
EmployeeList empList = new EmployeeList(employee);
empList.DisplayEmployees();
Scanner scanner = new Scanner(System.in);
System.out.println("0: quit, 1: add, 2: display");
String employees = scanner.next();
/* if (employees.equals("1")){
//not sure how to go back to displaying the user prompts
break;
} */
}
}
Few tips I can think of:
EmployeeList should not extend Employee. The main rule of OOP is that class A extends class B if B is a A. This is clearly not the case here - employeeList is not an employee, it's a list of employees (In my mind you don't need a class for this, just List<Employee>)
I'd separate the logic from the data. meaning - Employee class should only hold the employee's data, not deal with scanning and getting the input from the user. the constructor should be simple in my mind, something like:
public Employee(String name, int salary) {
this.name = name;
this.salary = salary;
}
The logic of getting the data should be outside of this class, either in an EmployeeHandler or in the main itself. Since you put it inside the employee, you are having troubles continuing when some of the logic is in the employee and some in the main.
the high-level code should be something like (I'll leave the details to you):
show the menu options to the user
if he wants to add user, get input for both variables, create the employee object and add it to the list
if he wants to display, go over the list and print (the printing can be done overriding toString in Employee class)
if he wants to quit, finish
continue this loop until he wants to quit
public class Employee {
private String Last_Name;
private int Salary;
public Employee(){
public String getLName(){
return Last_Name;
}
public void setLName(){
this.Last_Name = Last_Name;
}
public int getSalary(){
return salary;
}
public void setSalary(){
this.salary = salary;
}
}
}
then in your main method you can create the employee object.
public static void main(String[] args){
Employee employee = new Employee();
Scanner scanner = new Scanner(System.in);
employee.setLName = scanner.next();
employee.setSalary = scanner.nextInt();
}
If i were you I would just make an arraylist to hold all employees. I would prompt the input option for x amount of times and add to the end of the arraylist. the arraylist would be created as so
ArrayList<Employee> employeeList = new ArrayList<Employee>();
to add to it use add
employeeList.add(employee);
This should be able to get you started
EDIT:
OOPS, made several mistakes. edit with the following. Note that it is employee.setLastName(value) because the method setLastName is part of the employee class and it must be passed a value because we have defined that in the employee class.
Employee employee = new Employee();
Scanner scanner = new Scanner(System.in);
String tempName = scanner.next();
int tempSalary = scanner.nextInt();
employee.setLastName(tempName);
employee.setSalary(tempSalary);
EDIT 2:
try to print arraylists as follows. didnt test it. let me know how it works.
for (int i = 0; i< employeelist.size(); i++){
Employee temp = values.get(i);
System.out.println("Last Name: " + temp.getLname() + "Salary: " + temp.getSalary());
}
I modified my employee class to look like this:
public class Employee {
public String lastName;
private int salary;
public Employee(){
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
#Override
public String toString(){
return "Employee Last Name: " + lastName + "\n" + "Employee Salary: " + salary;
}
}
I have modified my EmployeeTest class:
This is my EmployeeTest class:
import java.util.ArrayList;
import java.util.Scanner;
public class EmployeeTest {
static ArrayList<Employee> employeeList = new ArrayList<Employee>();
public static void main(String[] args) {
for(int i=0;i<5;i++){
addEmployees(employeeList);
}
System.out.println(employeeList.toArray());
}
public static void addEmployees(ArrayList<Employee> employeeList){
Scanner scanner = new Scanner(System.in);
System.out.println("0: quit, 1: add, 2: display");
String options = scanner.next();
if(options.equals("1")){
System.out.print("Enter employee last name: ");
String lastname = scanner.next();
System.out.print("Enter Employee Salary: " + "£");
int salary = scanner.nextInt();
Employee employee = new Employee();
EmployeeList.add(employee);
}
else if(options.equals("2")){
for (Employee employee : employeeList){
/*System.out.println("Name: " + employee.getLastName() + ", " + "Salary: " + employee.getSalary());*/
System.out.println(employee);
}
}
else{
System.exit(0);
}
}
}
However when i press 2 as my options it doesn't display what is in my arraylist.
I had read that a toString method is used to get those details so i could print them to the screen. And that using this for loop gets each item in the list to display them. Am i missing something here?. Apologies for this dragging on a bit, im just wanting this to work.

Set , Get Method in Java

I am just starting to get into Object Oriented Programming in Java. I am curious about what the difference (if any) is between the 2 pieces of code below.
public class BuyAHouseInc
{
// Instance variables
private String firstName;
private String surname;
private String address;
private int budget;
// method to set the first name in the object
public void setFirstName(String firstName)
{
this.firstName = firstName; // stores the first name
}
// method to retrieve the first name from the object
public String getFirstName()
{
return firstName; // return value of first name to caller
}
// method to set the surname in the object
public void setSurname(String surname)
{
this.surname = surname; // stores the surname
}
// method to retrieve the surname from the object
public String getSurname()
{
return surname; // return the value of surname to caller
}
// method to set the address in the object
public void setAddress(String address)
{
this.address = address; // stores the address
}
// method to retrieve the address from the object
public String getAddress()
{
return address; // return the value of address to caller
}
// method to set the budget in the object
public void setBudget(int budget)
{
this.budget = budget; // store the budget
}
// method to retrieve the budget from the object
public int getBudget()
{
return budget; // return the value of address to caller
}
}
This is the 2nd piece of code;
public class BuyAHouseInc
{
public void displayClient(String firstName, String surname, String address, int budget)
{
System.out.println("Client Name: " + firstName + " " + surname);
System.out.println("Address: " + address);
System.out.println("Budget: " + "€" + budget);
}
}
I prefer the 2nd piece of code here because its clearer to understand but I have been reading a lot on methods and objects and I can't figure out what the actual differences are. Are set and get methods secure ways of entering values?
Let's start with what you think is the simpler code:
public class BuyAHouseInc
{
public void displayClient(String firstName, String surname, String address, int budget)
{
System.out.println("Client Name: " + firstName + " " + surname);
System.out.println("Address: " + address);
System.out.println("Budget: " + "€" + budget);
}
}
We could instantiate this class and use it like so:
public static void main(String[] args) {
BuyAHouseInc buyAHouseInc = new BuyAHouseInc();
buyAHouseInc.displayClient("jane", "doe", "123 main street", 100000);
}
The effect of this main method is to display the information on your screen. That's everything instances of this class can do. You can't share the information, or reuse it.
The first piece of code you show lets you create an object with fields that store data that you can reuse. The getters and setters are written so you can access those fields to use elsewhere in your program.
We can also add the displayClient method to this class, like so:
public class BuyAHouseInc {
private String firstName;
private String surname;
private String address;
private int budget;
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
...
public void displayClient() {
System.out.println("Client Name: " + this.firstName + " " + this.surname);
System.out.println("Address: " + this.address);
System.out.println("Budget: " + "€" + this.budget);
}
}
So then I might be able to write a program like this:
public class Solution {
public static void main(String[] args) {
BuyAHouseInc jane = new BuyAHouseInc("jane", "doe", "123 main street", 100000);
BuyAHouseInc john = new BuyAHouseInc("john", "doe", "123 main street", 50000);
System.out.println("The following clients can afford to buy a house");
if (canAffordTheHouse(jane)) {
jane.displayClient();
}
if (canAffordTheHouse(john)) {
john.displayClient();
}
}
public static boolean canAffordTheHouse(BuyAHouseInc client) {
return client.getBudget() > 50000;
}
}
If you're asking about getter / setter vs direct access, then there are many advantages of getter / setter over direct access.
Basically:
It's more secure as variable implementations should be kept private
and non accessible by public sources.
It allows for additional functionality in the get / set call and
allowing different behavior for whom is getting / setting.
It allows for different access levels (public, protected, etc.)
It is, however, the exact same speed as accessing directly.
Here is another answer that shows what I said in more detail.
You could combine the blocks of code
public class BuyAHouseInc
{
// Instance variables
private String firstName;
private String surname;
private String address;
private int budget;
public void displayClient()
{
System.out.println("Client Name: " + this.firstName + " " + this.surname);
System.out.println("Address: " + this.address);
System.out.println("Budget: " + "€" + this.budget);
}
// method to set the first name in the object
public void setFirstName(String firstName)
{
this.firstName = firstName; // stores the first name
}
// method to retrieve the first name from the object
public String getFirstName()
{
return firstName; // return value of first name to caller
}
// method to set the surname in the object
public void setSurname(String surname)
{
this.surname = surname; // stores the surname
}
// method to retrieve the surname from the object
public String getSurname()
{
return surname; // return the value of surname to caller
}
// method to set the address in the object
public void setAddress(String address)
{
this.address = address; // stores the address
}
// method to retrieve the address from the object
public String getAddress()
{
return address; // return the value of address to caller
}
// method to set the budget in the object
public void setBudget(int budget)
{
this.budget = budget; // store the budget
}
// method to retrieve the budget from the object
public int getBudget()
{
return budget; // return the value of address to caller
}
}
Alternatively, you could pass a whole object of BuyAHouseInc into the display function.
public void displayClient(BuyAHouseInc b)
{
System.out.println("Client Name: " + b.getFirstName()+ " " + b.getSurname());
System.out.println("Address: " + b.getAddress());
System.out.println("Budget: " + "€" + b.getBudget());
}
public void displayClient(String firstName, String surname, String address, int budget)
{
//........
}
is simply another method. Enclosed in { and } defines what it does when a call to displayClient() method is called. displayClient() requires 3 arguments before it can perform it's task. The arguments are what's inside the () in public void displayClient(String firstName, String surname, String address, int budget). The 2nd piece of code can be put within the public class BuyAHouse block or { }. Your setters() and getters() are also similar to displayClient() but has fewer arguments.
What's inside { } of public class BuyAHouse are members or methods. These methods has access to the class variables
private String firstName;
private String surname;
private String address;
private int budget;
That's why on most of the syntax of setters(), you can see that it's setting/assigning/storing (whatever you like) values to your class variables. So basically set() methods are used to modify the value of the variables firstname, surname,address and budget
getters() are used to return the value of the variables.
For instance,
String name; //this has no string value yet
//function definition - you tell what you want this method to do
public void setMyName(String yourName){
name = yourName; //you store the value of yourName to name
}
//method call
setMyName("whatever name you like"); // whatever name you like will be passed to the yourName variable

Displaying Group Name with Group Members

I am trying to solve an assignment in my Java class. I am stuck and need a little help.
I am trying to create a method in my Group class that will display the group name and the 4 students in the group. My code currently displays the group name and the memory location of my student inside my array.
public class Group {
/**-------Declaring attributes----*/
String groupName;
int newStudentCount;
/**----------------------------*/
/**--------Constructor------------*/
public Group(String givenGroupName) {
groupName = givenGroupName;
}
Student[] students = new Student[4];
/**----------------------------*/
/**--------Method------------*/
void addStudent(Student st) {
students[newStudentCount] = st;
++newStudentCount;
System.out.println("New student: " +st.getName());
}
public String getGroup() {
return "Group = " + groupName;
}
public Student getStudent(){
return students[0];
}
}
In my App class I have this:
public class App {
public static void main(String[] args) {
Group g1 = new Group("Pink Pony Princesses");
Student st1 = new Student("Joshua Mathews");
st1.getName();
g1.addStudent(st1);
Student st2 = new Student("Jame Brooks");
g1.addStudent(st2);
Student st3 = new Student("Mike Myers");
g1.addStudent(st3);
Student st4 = new Student("Christie Richie");
g1.addStudent(st4);
System.out.println(g1.getGroup()+ " " + g1.getStudent());
}
This is my Student class:
public class Student {
/**-------Declaring attributes----*/
String name;
String degree;
int age;
/**----------------------------*/
/**--------Constructor------------*/
Student(String givenName){
name = givenName;
}
Student(String givenName, String givenDegree, int givenAge) {
name = givenName;
degree = givenDegree;
age = givenAge;
}
/**--------- METHODS --------*/
//Array
public final String [] activities = {
"Working on Homework", "Playing a Game", "Taking a Nap"
};
String getInfo(){
return name + age + degree;
}
String getName() {
return name;
}
int getAge(){
return age;
}
String getDegree() {
return degree;
}
String whatsUp(){
Random rand = new Random();
int randomIndex = rand.nextInt(activities.length);
String returnActivity = activities[randomIndex];
return returnActivity;
}
I'm not sure how to call my array to display the 4 names, and not the memory location of them. Any help would be greatly appreciated.
I can deduce a couple of things from your question.
First, you are returning only the student at index 0 of the Student array held within your Group object. If you want to return all students your method signature should have a Student[] as the return type rather than a Student object.
If you follow the above prompt then you will have to iterate through the returned array printing each Student object.
Regardless of which implementation you choose the reason you print out a memory reference rather than a String object is that you have not overridden toString within your Student class.
Something like this will print out Student data when passed to a System.out call:
#Override
public String toString() {
return someStudentData;
}
You can go with what andrewdleach said by implementing toString(). OR
To print all student names your method should be something like:
public String getStudent(){
String studentNames = "";
for(Student stu: students){
studentNames+= stu.getName() + ",";
}
return studentNames;
}

Objected Oriented Programming- How to use the toString() method and format()?

I have just started doing object oriented programming as part of my course, but I am struggling with it, specifically the toString method in a Person Class. I need to write a toString() method to display the contents of instance variables.
I need to by sample print out:
Person[forName=joe, surname= smith, age= 25, height= 1.57, gender= male]
I also need to format it like this using the format method:
smith joe 25 1.57 male
davis sian 18 1.73 female
*** *** *** *** ***
I havent written a tester yet, but here is what I have written so far for the class and now I'm stuck, I'm not even sure if I am getting the toString statement wrong. I am using netBeans for this:
public class Person
{
private String surname;
private String forname;
private int age;
private double height;
private String gender;
public String toString()
{
return getClass().getName() + "[surname= " + surname + " forname= " + forname + " age= " + age + " height= " + height + " gender " + gender + "]";
}
}
What I need to do is make a class called Person that I can test. It needs to be able to hold the five variables above (surname etc) for different people. I need to be able to print out each of the instance variables with a toString() method and to use a format() method to produce a string with formatting infomation in order for the string printed out by the toString() method to be formatted like the second quotation.
Am I on the right track and regardless, how can I work through this?
EDIT: I have looked at the Person Class and have done what I can with it, does it seem decent enough? I am going to try and get a PersonTester together.
public class Person
{
private String surName;
private String forName;
private int age;
private double height;
private String gender;
#Override
public String toString()
{
return getClass().getName() + "[surName= " + surName + " forName= " + forName + " age= " + age + " height= " + height + " gender " + gender + "]";
}
public void format()
{
System.out.format("%10s%10s%10d%10f%10s", "surName", "forName", age, height, "gender");
}
public String getSurName()
{
return surName;
}
public String getForName()
{
return forName;
}
public int getAge()
{
return age;
}
public double getHeight()
{
return height;
}
public String getGender()
{
return gender;
}
public void setSurName(String surName)
{
this.surName = surName;
}
public void setForName(String forName)
{
this.forName = surName;
}
public void setAge(int age)
{
this.age = age;
}
public void setHeight(double height)
{
this.height = height;
}
public void setGender(String height)
{
this.gender = gender;
}
}
EDIT 2: Started on a class Tester, but I am running into errors again about the setter's not having a ; and not being a statement.
Here's the tester so far:
public class PersonTester
{
public static void main(String[] args)
{
System.out.println("PersonClassTester");
System.out.println("*****************");
System.out.println("");
Person joeSmith = new Person();
String "smith" = joeSmith.setSurName();
String "joe" = joeSmith.setForName();
int 25 = joeSmith.setAge();
double 1.57 = joeSmith.setHeight();
String "male" = joeSmith.setGender();
joeSmith.toString();
joeSmith.format();
}
}
First of all you have to noticed that every object you create extends class Object. This Object class contains methods like toString, equals, hashCode...
your object have also this methods(inherited from Object). When you override (you should annotate this method with #Override) for eg. toString you will always use this toString method instead of inherited one. Its called polymorphism. Your toString method looks fine. In your main method you should use some kind of loop through all Persons and there format the output from toString method.
You have error in your code
public String toString(); {
remove the ; after ()
public class Main {
public static void main(String[] args) {
Person a = new Person("smith", "joe", 25, 1.57, "male");
Person b = new Person("davis", "sian", 18, 1.73, "female");
List<Person> persons = new ArrayList<Person>();
persons.add(a);
persons.add(b);
for(Person p : persons){
System.out.format("%s %s %s %d %.2f %s", p.getClass().getName(), p.getSurname(), p.getForname(), p.getAge(), p.getHeight(), p.getGender());
System.out.println();
}
}
}
If you call this
System.out.println(p.toString());
than you ll get your person via toString method.
I just edit your Person class and add constructor and geters + seters
public Person(String surname, String forname, int age, double height,
String gender) {
super();
this.surname = surname;
this.forname = forname;
this.age = age;
this.height = height;
this.gender = gender;
}
Here is geter and seter sample.
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
As already mentioned your toString() is fine.
Please note that the toString() method and the format() method are IMO supposed to work independently as they do serve different purposes.
I suggest to put the format method not in the person class (or at least make it static method). This is because a single Person instance has not enough information for it to be printed in the table format. It at least needs to know the column widths. Otherwise you could end up with something like this:
smith joe 25 1.57 male
someVeryLongFirstName sian 18 1.73 female
*** *** *** *** ***
So the format method should take a list of persons that should be printed out and then first calculate the column widths. After this is done you then just pad the property value to the column width and print this out.
You are on the right track:
Inside of the Person class you need to add public methods for each private variable to set the data:
public void setAge(int age) {
this.age = age;
}
Then you can create a Person object in your main class and set his age:
public class Main {
public static void main(String[] args) {
Person p = new Person();
p.setAge(15);
}
}
As an alternative, you can use a constructor inside of your Person class to set your object's variables:
public Person(String surname, int age) {
this.surname = surname;
this.age = age;
}
And create the object in the main method like this:
Person p = new Person("Nillas", 25);
You can always run your toString() method in the main class after you've created the object and see the result:
System.out.println(p.toString());
Hope this helps, good luck!

Categories