In this homework of mine, in my main I have this line:
Lec.addStudent( "James" , "A1" , "BICT" );
In another class called LectureRoom:
import java.util.ArrayList;
public class LectureRoom{
private String courseName;
private String roomNumber;
private String Lecturer;
private ArrayList <Student> studentList;
public LectureRoom(String roomNumber , String courseName , String Lecturer)
{
this.courseName=courseName;
this.roomNumber=roomNumber;
this.Lecturer = Lecturer;
this.studentList = new ArrayList<Student>();
}
public void printStudents(){
System.out.println(studentList);
}
public void addStudent(String name, String id, String major)
{
Student s = new Student(name, id , major);
studentList.add(s);
}
public ArrayList<Student> getStudentsByMajor(String major)
{
ArrayList<Student> students = new ArrayList<>();
for (Student student : studentList) {
if (student.getMajor().equals(major))
students.add(student);
}
return students;
}
The outcome is to be:
Adding:James, A1, BICT
Normally, with a getter I would:
System.out.println("Adding:" + getStudentName() + ", " + getID() + ", " + getMajor() );
However in this case in method addStudent, I have created an object called "s" where it stores the name of the student, id and major.
Suppose I want to print all these 3 in a line, how can I do so?
I tried these in printStudents() method
1) System.out.println(studentList);
2) for(Student studentdetails : studentList)
{
System.out.println(studentdetails);
}
but both returned-
[Student#bf5743]
What is this error called and how can I solve it? Thanks!
You need to Override toString method in your class, and
#Override
public String toString() {
return String.format();// print your desired format.
}
Using System.out.println(obj) directory will print use the default toString method which returns:
object.getClass().getName() + "#" + Integer.toHexString(object.hashCode())
There are more solutions for this problem, but a quite simple one, could be overriding the method toString()
#Override
public String toString() {
return String.format("%s %s %s", s, id, major);
}
I'm assuming that your Student class has the attributes s, id and major that contain student name, id and major.
Have a look at the API for the Object class
Every class has Object as a superclass so your Student class under the covers basically extends Object at some point.
This is important as it means that every accessable method and field in Object is available to your Student class. You can see this in the ide you are using buy doing studentdetails. and see the list that comes up.
If methods in your hierarchy are not final and are accessable you can override them and add your own implementation.
Related
List<Student> studentList1 = [Student1,Student2,Student3]
Student1 and 2 and 3 are the models.
arg1 = id , arg2 = name
student1 = [5,"fsd"]
student2 = [7,"fsf]
student3 = [5,"fsd"]
If this is the scenario we need to remove duplicated objects here. Only student1 must be there or student 3 as values are same.
A new list with the unique objects is the ultimate ouput which is like below.
List studentList2 = [studentObject1,studentObject2]
Hello #arshiya this is the easiest solution I can come up with (there are others that come to mind, like using pointers with enhanced for loops, but that is much more complicated). It uses a new Set data structure which will do the removal of duplicates in the background (not explicitly coded by you), as long as you define "what is an equal student?" which happens in the equals() method. I recommend that you take the code below make them as two separate new Java classes and play around, see if this solution works for you.
Here is my Student class:
public class Student {
// Attributes
int id;
String name;
// Constructor/s
Student(int idGiven, String nameGiven) {
id = idGiven;
name = nameGiven;
}
// Methods
// Getters and Setters
public int getID() {
return this.id;
}
public void setID(int newID) {
id = newID;
System.out.println("ID changed from " + id + "to " + newID);
}
public String getName() {
return this.name;
}
public void setName(String newName) {
name = newName;
System.out.println("Name changed from " + name + "to " + newName);
}
// Required, the equals method as part of every object in Java can be overridden
// with the notation below.
#Override
public boolean equals(Object otherStudent) {
// Check if the object given is a student.
if (otherStudent instanceof Student) {
// Create a temporary student object so we avoid casting later.
Student checkedOtherStudent = (Student) otherStudent;
// If the names are the same then it is the same student. If you want you can do the
// exact same thing with the ID
if (this.name.equals(checkedOtherStudent.getName())) {
return true;
}
}
// If its not a student, print something to be aware of what happened
else {
System.out.println("Object provided is NOT a type of Student.");
}
return false;
}
// Required for using a set as part of the solution
#Override
public int hashCode() {
return name.hashCode();
}
// Optional, but allows you to view the output properly
#Override
public String toString() {
return "Student with name: " + name + " and id: " + id;
}
}
And my Main class:
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Main {
public static void main(String[] args) {
// Create example students and fill an ArrayList.
Student student1 = new Student(1, "Tamila");
Student student2 = new Student(2, "John");
Student student3 = new Student(3, "Tamila");
List<Student> studentList = new ArrayList<Student>();
studentList.add(student1);
studentList.add(student2);
studentList.add(student3);
// List before any changes
System.out.println(studentList);
// Set data structure will only allow unique elements inside by definition, so
// lets just add our arraylist into the set.
Set<Student> setOfStudents = new HashSet<Student>(studentList);
// Empty your student list
studentList.clear();
// Refill the student list only with the unique elements from the set
studentList.addAll(setOfStudents);
// Test our new list of students without duplicates
System.out.println(studentList);
}
}
I know some people may find the comments and the large variable names excessive, it's just that I do not know how well into Java the programmer on the other side is. Better to be detailed in my experience.
Please pardon my bad English
I am trying to create a HashMap with a String as a key, and an Object as parameter, which I want to initialise each time the program runs so that its added to a new key in the HashMap.
The problem is, that not all values are returned, and namely the second, gives back a weird output.
package javaex1;
import java.util.*;
public class Javaex1 {
public static void main(String[] args) {
Person obj = new Person("Eminem", "Male");
HashMap<String, Person> MapPerson = new HashMap<String, Person>();
MapPerson.put("Eminem", obj);
System.out.println(MapPerson);
}
}
The object
package javaex1;
public class Person {
String Name;
String Gender;
public Person (String name, String Gend) {
this.Name = name;
this.Gender = Gend;
}
public String getName() {
return Name;
}
public String getGender() {
return Gender;
}
}
Any help or hint is greatly appreciated! Thank you in advance for your time!
The expected results should be "Eminem Male". Instead what I get is this:
{Eminem=javaex1.Person#2a139a55}
This happens because you are trying to print an Object, An Object when printed gives the default toString implementaion of Object class , which is shown below
// implementation of toString in Object class
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
This is what you can see in your current output .
You should ovverride toString method in Person class like this.
public String toString() {
return this.Name + " " + this.Gender;
}
So that it returns the name and gender
You should override toString method in Person class. Like that:
#Override
public String toString() {
return this.Name + " " + this.Gender;
}
You're printing the MapPerson object, not the Person one.
Your code should be:
Person person = MapPerson.get("Eminem");
System.out.println(person.getName() + " " + person.getGender());
Create and implement a class Person. A Person has a firstName and friends. Store the names of the friends as a String, separated by spaces. Provide a constructor that constructs a Person with a given name (passed through arguments) and no friends. Provide the following methods:
public void befriend(Person p)
public void unfriend(Person p)
public String getFriendNames()
public int getFriendCount()
*Hint - you can use p.name to access the name of the Person passed to a method as an argument.
Include a Tester class to make sure your Person has some friends.
How do I store the names of the friends as a String, separated by spaces. (I have to be able to input the names from the main method). I also have no idea how to get rid of already inputted name using the method "unfriend"
public class Person
{
private String firstName;
private String friendNames;
private int friendCount;
public Person(String name)
{
firstName = name;
friendCount = 0;
}
public String getFriendNames()
{
return friendNames;
}
public double getFriendCount()
{
return friendCount;
}
public void befriend(String name)
{
friendNames = friendNames + " " + name;
friendCount++;
}
public void unfriend(String name)
{
String[] parseNames = friendNames.split(name);
friendNames = parseNames[0] + parseNames[1];
friendCount--;
}
}
Main Method:
public class PersonTester {
public static void main(String[] args) {
Person p = new Person("Alex");
p.befriend("John");
p.befriend("Alice");
p.befriend("Mike");
p.befriend("Annette");
p.unfriend("Alice");
System.out.println(p.getFriendCount());
System.out.println(p.getFriendNames());
}
}
Expected output:
2
John Mike
The problems you are having with the methods using the parameter(Person p) are because you have two different variables: friendName (which exists) and name (which does not). Changing the variable friendName to name will take care of some of the errors you are receiving.
(Also the method getFriendCount() returns friendsCount, but should return friendCount (you have an extra s in there) and your assignment calls for a method called befriend, not bestFriend.)
How to delete friends:
You can delete a friend by parsing the friend out of the friendNames string and then concatenating the two resulting strings back together:
public void unfriend(String name)
{
String[] parseNames = friendNames.split(name);
friendNames = parseNames[0] + parseNames[1];
friendCount--;
}
I would suggest changing befriend and unfriends parameters to accept a String instead of a Person object. Person already has access to its own object and in your main you are trying to pass them Strings anyways. Here is what befriend should look like:
public void befriend(String name) //Changed to "befriend"
{
friendNames = friendNames + " " + name;
friendCount++;
}
Also, you only need one constructor for Person, which should look like this:
public Person(String name)
{
firstName = name;
friendCount = 0;
}
When I run your program (using these changes) I get the following output:
2.0
John Mike
How do i return a string and an integer? say i wanted to return
students name which is an string and their mark which is an integer.
I cant do mark=mark+element+(element2+name); that creates an incompatible type.
My suggestion in this type of situation is to create a new class that holds this information. Name it for example StudentMark.
class StudentMark {
private final String name;
private final int mark;
public StudentMark(String name, int mark) {
this.name = name;
this.mark = mark;
}
public String getName() { return name; }
public int getMark() { return mark; }
}
Then in your method that has both the name and mark where you want to return, just do like so.
return new StudentMark("Samuel", 3.2);
Here you can also add any other interesting methods that you might need.
Create a class Student and return a student
class Student{
private String name;
private int mark;
//assessor+ contructors
}
you'll need to define a class for it. the class should have two attributes: a string and an int
Define a class that contains both values and return an object of that class.
create A class with priavte variables for name and marks. and override toString() method.
public class Student{
private int marks;
private String name;
//provde setters and getters for marks and name
public String toString(){
return getName()+getMarks();
}
}
In your Student class, you can have a method:
public String printNameAndGrade() {
return "Name: " + this.getName() + "\n " + "Grade: " + this.getGrade();
}
and then call it with a Student object reference:
Student st1 = new Student("Gabe Logan", 97);
System.out.println(st1.printNameAndGrade()); //use `println` method to display it.
You can use a two element Array or List and put the values in there. Unfortunately this looses all type Information.
You can use a Map which keeps the type information, but might be confusing because you would expect an arbitrary number of entries.
The cleanest option is to create a simple class with the two elements.
Hi i have the following code:
public List<Person> findAll() {
List<Person> copy = new ArrayList<Person>();
for (Person person : personer) {
copy.add(person);
}
return copy;
}
But when i test this i only retrieve the following and not the value:
[Person#15c7850, Person#1ded0fd,
Person#16a9d42]
How do i get the values and not like above. Where i am inserting the person the code looks like this:
public boolean insert(String name, String nbr) {
if (containsName(name)) {
return false;
}
Person person = new Person(name, nbr);
personer.add(person);
return true;
}
and here is my Person class:
class Person {
private String name;
private String nbr;
public Person (String name, String nbr) {
this.name = name;
this.nbr = nbr;
}
public String getName() {
return name;
}
public String getNumber() {
return nbr;
}
}
You're already receiving the objects you want.
What you see is an internal representation of these objects.
You must iterate through them and call their respective methods to see the information you probably want to see.
If you're not satisfied with these results, you must override toString to provide you with more meaningful information.
Update:
after seeing your edit, you should add toString similar to this one in your Person class:
#Override
public String toString() {
return "Name: " + name + ", number: " + nbr;
}
By the way, you're storing nbr as a string, and it's obvious it should be an integer. So, I'd suggest changing its type to an int or Integer.
You are getting a List object back. You can use the Person object to get the data that you need. To get to the Person objects, iterate over the list.
List<Person> people = findAll();
for Person p : people {
String phoneNumber = p.phoneNumber();
String name = p.Name();
}
Override the toString() method in the Person class if you want a better description when printing the results.
Put something like this in the class Person (don't change the method name!):
public String toString() {
return name;//change this line
}
You are printing out an Object that has the default toString inherited from the Object class. This will print out the type of object it is and its location in memory (ie: Person#1ded0fd).
If you'd like it to see something else, you can override the toString method within your class:
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public String toString() {
return this.name;
}
}
If your class looked like the above, this would allow you to do something like this:
Person p = new Person("John");
System.out.println(p);
> John
You can also just grab it as is and print out any information you want from it without overriding the toString method.
Person p = new Person("John");
System.out.println(p.getName());
> John
What value or class Person's property you aspect to retrieve from the ArrayList? This kind of value(Person#15c7850, etc) shows that the Person's object random id that assigned by JVM when you use
System.out.print(copy).