How to put a object in a linked list? - java

I'm trying to make a bank record and trying to use linked list. I made my bank class and I'm trying to put that as an object in my main class and print the output. So If I enter James as a first name, black as my last name and 200 as balance. It should print the output: FirstName: James, Lastname: Black, Balance: 200. If I add another first,last, balance. It should print the new record with the old record.
Example:
First name Lastname Balance
James Shown 4000
Kyle Waffle 2000
Bank Class:
public class Customer2 {
String Firstname,Lastname;
public int balance, amount;
int total=0;
int total2=0;
Scanner input = new Scanner(System.in);
public Customer2(String n, String l, int b){
Firstname=n;
Lastname=l;
balance=b;
}
public void withdraw(int amount){
total=balance-amount;
balance=total;
}
public void deposit(int amount){
total=balance+amount;
balance=total;
}
public void display(){
System.out.println("FirstName: "+" Lastname: "+" Balance");
System.out.println(Firstname+" "+Lastname+" " +balance);
}
Main class:
LinkedList<Customer2> list = new LinkedList<Customer2>();
list.add("Bob");
list.getfirst("Lastname");

You should create a new customer2 Object and then add that to your linked list
It would look like this:
Main Class:
Customer2 customer = new Customer2("Bob", "Doe", 1000);
list.add(customer);
Bob would now be added to the linked list.
If you wanted to retrieve bob from the linked list you could iterate through the list until you found bob and then call display on that object.
Or you could use getFirst (if bob is the first in the list)
that would look like this:
list.getFirst().display();
There are other methods in the linked list class that you can use to add or get if you know the position. Here is a link: http://www.tutorialspoint.com/java/java_linkedlist_class.htm
also I think this is what you wanted your display() method to be:
public void display(){
System.out.println("First Name: " + firstName + ", Last Name: " + lastName + ", Balance: " + balance);
you should also use lower case letters to start variable names as it is good naming convention aka. Firstname becomes firstname.

If you want to put element in LinkedList<Customer2> list you need use method list.add(customer) where customer is object from class Customer2.

LinkedList<Customer2> list = new LinkedList<Customer2>();
Customer2 c = new Customer2("firstName","lastName",1000);
list.add(c);
System.out.println(list);
Override toString() in Customer2 Class:
#Override
public String toString(){
return "FirstName: "+fristName+",lastName: "+lastName,+"balance" +balance;
}
//toString()
//returns string for the object
to print all the objects in list, each Customer2 object in a new line
for(Customer2 c : list){
System.out.println(c);
}

Related

How do I find the smallest variable from a list of objects? (JAVA)

The code doesn't show any errors. However, I am getting an unexpected output. I am supposed to get the smallest number for age, but what I keep getting is the last value entered for age. Can you help me point out the mistakes in this code?
Maybe there is some logical error in the getYoungestPet() method?
package pet;
public class Pet
{
public static String petName;
public static int petAge, petWeight;
int youngestAge=9999;
static int test;
public static String setPetName()
{
return petName;
}
public int setPetAge()
{
return petAge;
}
public int setPetWeight()
{
return petWeight;
}
public int getYoungestPet() //probably an error here..?
{
if (petAge<youngestAge)
youngestAge=petAge;
return youngestAge;
}
}
package pet;
import java.util.Scanner;
public class PetMain extends Pet
{
public static void main(String[] args)
{
System.out.println("How many pets do you want to enter? " );
Scanner data= new Scanner(System.in);
int petNumber=data.nextInt();
for (int i = 1;i<=petNumber; i++)
{
Pet PetObject = new Pet();
System.out.println("Please enter name for Pet " + i );
Scanner input = new Scanner(System.in);
petName= input.next();
System.out.println("Your pet's name is : " + petName);
System.out.println(" ");
System.out.println("Please enter " + petName + "'s Age" );
petAge= input.nextInt();
System.out.println("Your pet's age is : " + petAge);
System.out.println(" ");
System.out.println("Please enter " + petName + "'s Weight" );
petWeight= input.nextInt();
System.out.println("Your pet's weight is : " + petWeight);
System.out.println(" ");
System.out.println(PetObject.getYoungestPet());
}
}
}
The code is supposed to show the smallest age but it shows the latest entered age.
you should declare youngestAge as static variable. so that all of the petObject could share the same value.
static int youngestAge=9999;
your setter and getter methods are also not proper.
public static String setPetName()
{
return petName;
}
should be:
public static void setPetName(String name)
{
petName=name;
}
Also don't forget to set values into PetObject from main method.
...
petName= input.next();
PetObject.setPetName(petName);
...
There are many things that are problematic with this code.
But just to answer your question directly, think about how many pet objects there could be in this program if every time the for loop runs it recreates the pet object because it is inside the for loop.
however, simply moving it outside the for loop will not help because then you will simply keep resetting the values of the same pet object every time you run the for loop.
Consider making an array of pet objects.
Also, your code never actually accesses the pet objects instance variables
In addition, there are other problems with your use of static as others have pointed out.
cheers.
Each time you are creating a Pet, you are getting a different youngestAge with value 9999 for that object. So each time it is comparing the latest petAge with 9999 and giving you the latest petAge as your enterd petAge is less than 9999.
If you need to store the smallest age, then keep it in a static field. Cause, keeping an extra field to store the smallest age for all object is redundant for memory.
If you want your desired output with the existing design, then do this:
Make youngestAge static:
static int youngestAge=9999;
And also don't forget to make the method static too. There is no need to make it object property anymore, both the field variables, it is using, are static.
public static int getYoungestPet()
{
if (petAge<youngestAge)
youngestAge=petAge;
return youngestAge;
}

Display List of Friends of Array

Sorry for including so much in here I just do not know where to begin as I am new to Java and I am lost on how to Display an Entire List of Friends once I have inputed them into the array. I need to use a for loop to do this.
Add a toString method to your Friend class like:
#Override
public String toString() {
return "Friend [firstName=" + firstName + ", firstAge=" + firstAge + "]";
}
So when you call System.out.println() you will get a human readable format and not the hashcode.
I would also suggest you move the line :System.out.println("\nYou have added the following friends:"); out of the for loop.
You can remove the entry from the list like:
public void removeFriend()
{
System.out.println("Please enter Name of person you would like to remove: ");
String name = input.nextLine();
Iterator<Friend> it = friendList.iterator();
while(it.hasNext()){
Friend f = it.next();
if(f.getName().equals(name)){
it.remove();
}
}
}

Java toString Method - Not printing correctly

I'm trying to get the toString from the class Employee, but all it does is give me an output of [ ]. I got the input for the toString method, but any ideas on how to get it to carry out to the output?
public class A5
{ // begin class
public static void main(String[] args)
{ // begin main
// ********** CREATE OBJECTS **********
ArrayList<Employee> employeeInfo = new ArrayList<Employee>();
// ********** GET INPUT **********
// get the employee's ID
System.out.println("\nEnter your employee ID.");
ID = keyboard.nextInt(); //get the input and set it to the local varaible ID
//System.out.println("Employee ID: " + ID);
// get the employee's hours worked
System.out.println("\nEnter the amount of hours you worked this week.");
Hours = keyboard.nextInt(); //get the input and set it to the local varaible HoursWorked
//System.out.println("Hours worked: " + Hours);
// get the employee's wage
System.out.println("\nEnter your wage.");
Wage = keyboard.nextDouble(); //get the input and set it to the local varaible Wage
//System.out.println("Employee wage: " + Wage);
// ********** OUTPUT **********
System.out.println(employeeInfo.toString());
// ********** CLOSING MESSAGE **********
System.out.println("\nEnd of Processing!");
} // end main
} // end class
And the other class is:
public class Employee
{ // begin class
private int ID; // employee's id
private int Hours; // number of hours worked
private double Wage; // pay per hour
public Employee(int IDnumber)
{
ID = IDnumber;
}
public int getID()
{
return ID;
}
public void setWage(double HourlyWage)
{
Wage = HourlyWage;
}
public double getWage()
{
return Wage;
}
public void setHours(int hoursWorked)
{
Hours = hoursWorked;
}
public double getHours()
{
return Hours;
}
public String toString() // overrides the toString method inherited from object
{ // begin toString
String strout = "\nId \t\t Hours \t\t Rate \t\t Regular Pay \t Overtime Pay \t Gross Pay\n";
strout += ID + "\t " + Hours + "\t\t\t $" + (df1.format(Wage)));
return strout;
} // end toString
} // end class
You are calling the toString method of the ArrayList, not of any Employee. In fact you did not yet create an instance of that class. Try:
System.out.println(new Employee());
EDIT:
First:
OK, well, you need atleast to make some Employee objects and add them to your list ;) Otherwise, there is "nothing" (which prints out to "nothing"). So after you read all your stuff from the user's input (ID and so) make a new Employee out of it:
// make a new employee
Employee employee = new Employee(id); // pass your id
employee.setWage(...); // pass your wage
... // pass other things
// add it to the list of course
employeeInfo.add(employee);
Now there is an employee in the list which you can print. You can test if something is on the list by asking for its size:
System.out.println(employeeInfo.size());
Second:
You don't call toString() on your employee class, which you properly want to print. You call it on your list of employees. Therefor you will see the result of the toString() method of the ArrayList class (which is not what you expect, but what is correct). Instead, iterate over the list and print every employee. Note that the toString() method will be called automatically, since System.out.println will convert your object to a string (which actually means to call this method).
Try this:
for(Employee employee: employeeInfo)
System.out.println(employee);
Your employeeInfo object seems to be empty, and thus you are printing an empty list.
Make sure you put values in it before printing.
Note that the toString() of the ArrayList is implemented to recursively invoke toString() of its object, so it is fine to use ArrayList.toString() to print the entire ArrayList - if that's what you want. No need to iterate for all elements.
You are printing the toString of an Array. employeeInfo is an ArrayList of Employees.
Iterate and print employees like:
for (Employee e : employeeInfo)
{
System.out.println(e.toString());
}

how do i add or delete something from an array?

I am writing this program that will take in the names, ages and salaries for 5 different people from the user and will put them in an array.
I then want to write a method that will ask the user for another name, age and salary and add that into the array. Also a method that will as for the name of someone who's already in the array and will delete the information of the person with that age from the array.
The first method will increase the array size by 1 and the second will decrease the array size by 1. so far this is what I have:
ArrayList<details> details = new ArrayList<details>();
for(int x = 0; x < 4; x++) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the first name: ");
String firstName = scan.nextLine();
System.out.println("Enter the last name: ");
String lastName = scan.nextLine();
System.out.println("Enter the age: ");
int age = scan.nextInt();
System.out.println("Enter the salary: ");
double salary = scan.nextDouble();
details.add (new details(firstName, lastName, age, salary));
}
I don't know how to go about doing this. I need some help!
thanks!
You can have a class Person with the class variables you require (name,age,salary)
class Person {
private int age;
private dobule salary;
private String firstname;
private String lastname;
}
Define the getter and setter methods for each of the class variables. For e.g
public void setAge(int age){
this.age = age;
}
public int getAge(){
return this.age;
}
In your main class read the input from STDIN as you are doing it. Instantiate the Person object for each of the 5 person.
Person employee = new Person();
employee.setAge(x);
employee.setFirstName(x);
employee.setLastName(y);
employee.setSalary(y);
Now, you can add each Person to your list and remove them too.
For removing any Person you would have to search for the Person through the ArrayList by name. That would be iterating over the length of ArrayList and comparing the name of each.
The final class would look like,
public class Solution{
private ArrayList<Person> details = new ArrayList()<Person>;
public static void main(){
// Here you loop for reading from STDIN as you are already doing.
// addPerson() would be used to add to ArrayList and removePerson() for the other
}
public addPerson(String firstName, String lastName, int age, int salary){
//Create the Person object
details.add(<person object>);
}
public removePerson(name){
details.remove(index);
// to get index it would require iterating over the ArrayList.
// It would be better if you use a Map instead (as other suggest)
// with name as the key
}
}
Hope this helps.
dud first of all, i can see that u have used arrayList name & Class name both same so please update that.
secondary use Map in place of Class like in if condition
if(){
Map userDetails = new HashMap();
map.put("firstname",firstname);
..
..
map.put("salary",scan.nextDouble());
details.add(map)
}
and on time of delete iterate ArrayList
for(int i=0;i<details.size();i++){
Map tempMap = details.get(i);
if(temp.get("firstname").toString() == "Given Name"){
}else{
// your logic
}
}
Hope will help you please let me know if any doubts.
use this code for removing employee
void removeEmployee(String name){
for(Employee emp :details){
if(name.equals(emp.getName())){
details.remove(emp);
break;
}
}
}
and do include exception handling

print toString() from another class

I asked a question earlier on this same project but I'm still having issues that I can't get through.
The project has a Person class, Validator class, Customer class, and Employee class. The Person class stores data about the person (name, email) the Customer class extends the person class and adds a customer number to the toString method. The Employee class also extends the Person class and extends a social security number to the toString method by overriding it.
At the bottom of the page I am trying to print the toString methods from my customer class OR my employee class. I want to make sure I am printing the right class based on what the user selected (if they are entering customer info or employee info)
The assignment specifically says "To print the data for an object to the console, this application should use a static method named print that accepts a Person object."
I think I have it started but I'm getting all kinds of red lines under what I have coded. Starting around the
public void toString()
line down towards the bottom.
I'm starting to think I am getting deeper into trouble by looking it up online so if someone can help me through it I would be greatful. My book doesn't show much on how to do this and all of the examples it shows seem to create the input and then print it but I'm trying to get the input from a user so I'm getting confused.
import java.util.Scanner;
public class PersonApp
{
public static void main(String[] args)
{
//welcome user to person tester
System.out.println("Welcome to the Person Tester Application");
System.out.println();
Scanner in = new Scanner(System.in);
//set choice to y
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
//prompt user to enter customer or employee
System.out.println("Create customer or employee (c/e): ");
String input = in.nextLine();
if (input.equalsIgnoreCase("c"))
{
String firstName = Validator.getString(in, "Enter first name: ");
String lastName = Validator.getString(in, "Enter last name: ");
String email = Validator.getEmail(in, "Enter email address: ");
String custNumber = Validator.getString(in, "Customer number: ");
Customer customer = new Customer(firstName, lastName, email, custNumber);
}
else if(input.equalsIgnoreCase("e"))
{
String firstName = Validator.getString(in, "Enter first name: ");
String lastName = Validator.getString(in, "Enter last name: ");
String email = Validator.getEmail(in, "Enter email address: ");
int empSoc = Validator.getInt(in, "Social security number: ");
Employee employee = new Employee(firstName, lastName, email, empSoc);
}
public void toString()
{
Person p;
p = c;
System.out.println(c.toString());
p = e;
System.out.println(e.toString());
}
System.out.println("Continue? y/n: ");
choice = in.nextLine();
System.out.println();
}
}
}
You can't define methods inside another method. The way you have the brackets, toString is defined inside main, which is illegal.
Also, you can't have toString return void, since it overrides the toString method from Object. Rename your method or have it return a String.
Your toString method needs to be moved out of your main method. It also needs to return a string. You'll probably have to call the method by some other name. Also, if Employee and Validator are in a separate package structure, you'll have to import that

Categories