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..
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
In our current chapter we are using arrays which I'm having some trouble creating a listing to be called upon from another class.
Goal: Display the parallel arrays from another class, this can be singular or in a group.
Question: Best or efficient way to call on a multi-parallel array with different data types?
Error: Starts with an illegal statement, as previously instructed here is the whole code, please ignore the loop display I was just testing to make sure the arrays were setup correctly.
Thanks Everyone, Yet again any assistance is much appreciated
import java.util.ArrayList;
public class Employee {
public static void main(String[] args) {
// create an array with employee number, first name, last name, wage, and Skill
int[] empID = {1001, 1002, 1003};
String[] firstName = {"Barry", "Bruce", "Selina"};
String[] lastName = {"Allen", "Wayne", "Kyle"};
double[] wage = {10.45, 22.50, 18.20};
String[] skill = {"Delivery Specialist", "Crime Prevention", "Feline Therapist"};
/*
for ( int i = 0; i < empID.length; i++ )
{
System.out.print( "Employee ID: " + empID[i] + "\n");
System.out.print( "First Name: " + firstName[i] + "\n");
System.out.print( "Last Name: " + lastName[i] + "\n");
System.out.print( "Hourly Wage: $" + wage[i] + "\n");
System.out.print( "Skill: " +skill[i] );
System.out.println("\n");
}
*/
//create an object to be called upon from another class
public ArrayList<int, String, String, double, String> getEmployee() {
ArrayList<int, String, String, double, String> employeeList = new ArrayList<int, String, String, double, String>();
employeeList.add(empID);
employeeList.add(firstName);
employeeList.add(lastName);
employeeList.add(wage);
employeeList.add(skill);
return employeeList;
}
}
} //end of class
First, you can't declare an ArrayList like this:
ArrayList<int, String, String, double, String>
If you want that, you can create your own object, create a class which can take these values, then you can create an ArrayList of this Object for example:
class MyClass{
int att1;
String att2;
String att3;
double att4;
String att5;
public MyClass(int att1, String att2, String att3, double att4, String att5) {
this.att1 = att1;
this.att2 = att2;
this.att3 = att3;
this.att4 = att4;
this.att5 = att5;
}
}
Then you can create an ArrayList like this :
List<MyClass> list = new ArrayList<>();
Going back to the basics of Java, it is an object oriented programming language so you should always aim to abstract "things" into an object if possible. You should encapsulate all of the common properties about an 'employee' into a class with all of the data as fields.
As the answer above shows, creating an ArrayList<MyClass> is the proper way of initialising arraylists as they can only take ONE type of data. You may have seen other classes take multiple types such as HashMap<Type1, Type2> but these are for a specified reason. Make sure to check the API doc first!
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();
}
}
}
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'm trying to output a string from an Object that has been passed into a set. The Following line is where my problem lies. It outputs [alex, jane] but with correct formatting I believe it should be outputted at alex jane. i.e. without the comma separated value and the brackets from the array.
System.out.print(module.getStudents() + " ");
I've tried various solutions including:
System.out.prinf(%s, module.getStudents() + " ");
and
System.out.prinln(module.getStudents().[whatever Netbeans makes available] + " ");
To help you better understand the problem. The idea of the application so far is to allow a user to search for a mosule ans return all students connected to it. The full source code bar the driver is:
import java.util.*;
public class Control {
public void run() {
Student jane = new Student("jane");
Student alex = new Student("alex");
Set<Student> students = new HashSet<Student>();
students.add(jane);
students.add(alex);
Module ufce1 = new Module("UFCE1");
Module ufce2 = new Module("UFCE2");
Set<Module> modules = new HashSet<Module>();
modules.add(ufce1);
modules.add(ufce2);
jane.addModule(ufce1);
jane.addModule(ufce2);
alex.addModule(ufce2);
ufce1.addStudent(jane);
ufce2.addStudent(jane);
ufce2.addStudent(alex);
System.out.println("Search module code: ");
Scanner scan = new Scanner(System.in);
scan = new Scanner(System.in);
String searchModule = scan.nextLine().trim();
for (Module module : modules) {
if (searchModule.equalsIgnoreCase(module.getName())) {
Iterator it = students.iterator();
Student student = (Student) it.next();
if (student.getModules().contains(module)) {
System.out.print(student + " ");
}
}
}
}
}
Module Class:
import java.util.HashSet;
import java.util.Set;
public class Module {
private String name;
private Set<Student> students = new HashSet<Student>();
public Module(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void addStudent(Student student){
students.add(student);
}
public Set<Student> getStudents() {
return students;
}
#Override
public String toString() {
return name;
}
}
Student Class:
import java.util.HashSet;
import java.util.Set;
public class Student {
private String name;
private Set<Module> modules = new HashSet<Module>();
public Student(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void addModule(Module module){
modules.add(module);
}
public Set<Module> getModules() {
return modules;
}
#Override
public String toString() {
return name;
}
}
When you do this System.out.print(module.getStudents() + " "); you're implicitly calling the toString method on the HashSet instance. So to get the formatting you want, you have 2 choices:
iterate over the set and print it the way you want
Subclass HashSet and override toString to display the way you want it.
The problem is that getStudents returns a Set object (a HashSet, to be specific). HashSet, in turn, inherits a toString() method from AbstractCollection which behaves as follows:
Returns a string representation of this collection. The string representation consists of a list of the collection's elements in the order they are returned by its iterator, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (comma and space). Elements are converted to strings as by String.valueOf(Object).
You'll need to write your own method for converting a set of students into the format you want, or else you can doctor up the value returned by the default toString implementation.
The brackets and the commas are coming from the toString() call on the Set. If you look in the source code of this method, you will see that it adds those. You can override the toString() method of the Set in your Module class, or just not printing the Set directly but manually looping over all elements and printing them one by one
#Chris gave an excellent solution in resolving your issues. There is however another one that I see more easy to implement and it is the following:
public String formatOutputString(){
String setStrings = module.getStudents();
// Get rid of opening bracket
String formatedString = setStrings.replace("[", "");
// Get rid of closing bracket
formatedString = setStrings.replace("]", "");
// Replace commas by spaces
formatedString = setStrings.replace(",", " ");
return formatedString;
}