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();
}
}
}
Related
HashSet<Soldier> soldiers; // it has name, rank, description
#Override
public String toString(){
return "Team: " + teamName + "\n" + "Rank: " + getRanking(soldiers) + "\n"
+ "Team Members Names are: "+"\n" + soldiers.iterator().hasNext();
//last line doesn't work
// I also tried soldiers.forEach(System.out::println) but doesn't work
}
Can anyone please how I can print all the name from Hashset in overriden toString method. Thanks
If you use java 8. It's simple to do with stream API:
public class Test {
public static void main(String[] args) {
Set<String> strings = new HashSet<>();
strings.add("111");
strings.add("113");
strings.add("112");
strings.add("114");
String contactString = strings.stream().map(String::toString).collect(Collectors.joining(","));
}
}
If you want change a delimiter you should replace Collectiors.joining(",") code to what you need. See also documentation by StringJoiner
For your class Soldier which has method getName():
Set<Soldier> soldiers = new HashSet<>();
String soldierNames = soldiers.stream().map(Soldier::getName).collect(Collectors.joining("\n"));
You will get a next result:
Din
Mark
David
... values from the soldiers set
hasNext() does only return a boolean indicating if the Iterator is finished or not.
You still have to call next() (in a loop) to get the next value(s).
See: https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
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);
}
So, i have a class named Hospital and a method called InsertFolders inside the Hospital class.
Inside the method the user must fill an array(max 5) of examinations (I made a class called Folders where i have the set and get methods for the array).
Now i have created another method called print where i want to print this array.
Note that there is an array of objects which contains the Folders.
ListOfFolders[i].getNameOfFolder(this is the field of the folder's name for example).
Is there a way where i can print the array?
For example when i try ListOfFolders[i].getArrayOfExaminations() it doesn't print the expected examinations.
Just override toString function like:
public class Person{
private int id;
private String firstName;
private String lasrName;
.
.
public Person(){
this.id = 1;
this.firstName = "First Name";
this.lastName = "Last Name";
}
public String toString(){
String str = "";
str += "Person Info: \n";
str += "Id : " + id + "\n";
str += "First Name : " + firstName + "\n";
str += "Last Name : " + lastName + "\n";
....
return str;
}
}
If you would share us your code I would have implement it better, but this is the idea.
Usage:
List<YourClass> list = new ArrayList<YourClass>();
list.add(new Person());
for (YourClass item : list){
System.out.println(item); //here it will automaticly use the overridden toString in your class
}
Output:
Person Info:
Id: 1
First Name
Last Name
Just printing an object prints the reference (~address) to it by default. You need to override the toString() method for the object to make it print the proper value.
If this is the default array in Java, you can loop over the objects in the array with the for(item : array) syntax.
Ok, now I think I've given up all hope of finding solution to what should to be a simple problem. Basically, I'm creating a students' record system that stores students' details in an ArrayList. I first created a constructor in the Student class to specify what entries each student will have. I then created an instance of the Student class in the main class (i.e. class with the main method) and then added the student object to the studentList ArrayList.
By the way, instead of hard-coding the student details, my initial aim was to let the user enter the details and then I'll use a Scanner or BufferedReader object to get the details stored in the Student object, and then to the ArrayList but I'm having trouble with that as well; so I'll probably tackle that problem as soon as I'm done with this one.
Anyway, I'm expecting the output to print out the students' details but instead I get a memory location (i.e. [studentrecordsys.Student#15c7850]). I'm aware that I need to override the toString method but how exactly this is done is what I can't seem to get. I get syntax errors everywhere as soon as I enter the #Override code block for the toString method. Here's what I've tried:
import java.util.*;
class Student {
private String studentID;
private String studentName;
private String studentAddress;
private String studentMajor;
private int studentAge;
private double studentGPA;
Student (String studentID, String studentName, String studentAddress, String
studentMajor, int studentAge, double studentGPA){
this.studentID=studentID;
this.studentName=studentName;
this.studentAddress=studentAddress;
this.studentMajor=studentMajor;
this.studentAge=studentAge;
this.studentGPA=studentGPA;
}
}
public static void main(String[] args) {
Student ali = new Student("A0123", "Ali", "13 Bond Street", "BSc Software Engineering", 22, 3.79);
List<Student> studentList = new ArrayList<>();
studentList.add(ali);
#Override
String toString() {
StringBuilder builder = new StringBuilder();
builder.append(ali).append(studentList);
return builder.toString();
}
System.out.println(builder);
}
You need to implement the toString() on the Student object.
public class Student {
...
Your existing code
...
#Override
public String toString() {
return studentID + ", " + studentName + ", " + //The remaining fields
}
}
then in your main method, call
for (Student student : studentList) {
System.out.println(student.toString());
}
You to override toString method because it is going to give you clear information about the object in readable format that you can understand.
The merit about overriding toString:
Help the programmer for logging and debugging of Java program
Since toString is defined in java.lang.Object and does not give valuable information, so it is
good practice to override it for subclasses.
Source and Read more about overriding toString
public String toString() {
return "Studnet ID: " + this.studentID + ", Student Name:"
+ this.studentName+ ", Studnet Address: " + this.studentAddress
+ "Major" + this.studentMajor + "Age" + this.studentAge
+ GPA" + this.studentGPA ;
}
You get errors because you have to Override the toString method inside the class you want to use it for. i.e you have to put the method, with the #Override inside your Student class.
And you can call it like this:
System.out.println(studentA.toString());
System.out.println(studentB.toString());
or in a loop:
for(Student x : studentList)
System.out.println(x.toString());
and so on..
Also, in your code you create a method inside your main method. Of course you will get errors.
I am trying to get this program to get the passwords from an array list.
import java.util.ArrayList;
public class CompanyDatabase {
public ArrayList<Person> getPeople() {
ArrayList<Person> people = new ArrayList<Person>();
String[] u = {"Joe","Stan","Leo","John","Sara","Lauren"};
String[] p = {"pass4321", "asdfjkl", "genericpw", "13579", "helloworld", "companypass"};
for(int j = 0; j < u.length; j++){
Person temp = new Person(u[j],p[j]);
people.add(temp);
}
return people;
}
}
import java.util.ArrayList;
import java.util.Scanner;
public class CompanyDatabaseDriver {
private static Scanner scan = new Scanner( System.in ) );
public static void main(String args[]) {
CompanyDatabase bcData = new CompanyDatabase();
ArrayList<Person> people = bcData.getPeople();
// what i tried
System.out.println(bcData.getPeople());
// also tried this
System.out.println(people.get(1));
}
}
The output is
[Person#1c9b9ca, Person#c4aad3, Person#1ab28fe, Person#105738, Person#ce5b1c, Person#1bfc93a]
or just
Person#1995d80
for the 2nd thing I tried.
The specific number / letter combination seems to change each time the program is run. Is there a way to specify which string to display from the array list?
Override toString() in the Person class
What you are seeing is the String returned by Object's default toString() method which is the name of the class followed by its hashcode. You will want to override this method and give the Person class a decent toString() method override.
e.g.,
// assuming Person has a name and a password field
#Override
public String toString() {
return name + ": " + password; // + other field contents?
}
Edit: if you only want to display one field in your output, then use Dave Newton's good solution (1+).
Yes; print the object property you want to see:
out.println(people.get(0).getFirstName());
the default implementation when you print List is to call toString for all objects in this List. and because you don't override toString method, it will call the default toString from Object class, that will print objects hashCode in hexadecimal notation, so you get this result:
Person#1c9b9ca ( classname#hashcode) , and it can be changed every time you execute the application because this hashcode come from memory address of the object).
so one option, is to override toString in your class
#Override
public String toString() {
return String.format("First name %s, Last name %s", firstName, lastName);
}
and call
System.out.println(yourList); // this will print toString for each object
the other option, is to print these attributes when you iterate on the List
for(Person person: persons) {
System.out.println("Person first name: " + person.getFirstName() + " , Last Name: " + person.getLastName());
}
In the first print statement you are trying to print the object..that is why you always see different number/letter combination..