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.
Related
I have the class Student with a constructor that sets the values int s_code, String name and int age.
When I create an object of the class Student I pass it into an ArrayList AllStudents.
My problem is that I want the user to enter an Id and check if there is that Id in the ArrayList. If its not let him add a new student else tell him to try again.
I tried to loop through the ArrayList with for and inside of it
I have an if statement with .contains and if it is true I have a simple println("Good") just to test it.
When I run my program though it skips it.
Here is my code:
static ArrayList<Student> AllStudents = new ArrayList<Student>();
static void InitStudents() //this is a method that creates some students when I call it in main.
{
AllStudents.add(new Student(1,"James",15));
AllStudents.add(new Student(2,"John",16));
AllStudents.add(new Student(3,"Rose",15));
}
System.out.println("Enter the ID of the student you want to add.");
Scanner get_new_code = new Scanner(System.in);
int s_code = get_new_code.nextInt();
for(Student code : AllStudents)
{
if (AllStudents.contains(s_code)) //I think that I have to include age and name for it to work.
{
System.out.println("Good");
}
}
By the way sorry if I didn't explain something or I did something completely wrong I'm new to Java.
That advanced loop is not helping you in the way you implemented it.
for(Student code : AllStudents){ //"code" is one element out of the list
if (AllStudents.contains(s_code)){ //here you are checking the whole list
System.out.println("Good");
}
}
This might be what you are looking for:
for(Student code : AllStudents){
if(code.getSCode() == s_code){ //here the one element named "code",
//out of the list, will be checked
System.out.println("Good");
}
}
A getter method (this one is called for example getSCode()) will help you here, to ask for every attribute of a student object. It will return the s_code of the object you are looking at.
EDIT AS EXAMPLE:
public class Student{
int s_code;
String name;
int age;
public Student(int code, String name, int age){
this.s_code = code;
this.name = name;
this.age = age;
}
public int getSCode(){
return s_code;
}
public int setSCode(int newSCode){
this.s_code = newSCode;
}
}
With the getter and setter you can ask for data of an object or you can set the data.
AllStudents contains students and s_code is an int.
You can search by id mapping it first. Assuming the code is in a field called Id.
allStudents.stream().map(s -> Student::getId).collect(Collectors.toList()).contains(s_code);
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 am trying to write a class called Student that is supposed to work with a StudentDriver. However, I am having a very hard time wrapping my head around the concept of methods and classes. I do not know how to receive and return data. Moreover, I don't even know if I am declaring my data correctly. Please help me. I would greatly appreciate it.
Also when I compiled the Student it says that it cannot find the symbol this.setGPA. How so? When in the driver it has .setGPA.
Thank you.
// This will be the "driver" class for the Student class created in
// MinilabWritingClasses (It looks very complicated because of all
// the comments, but it really just creates instances of Student and
// tells them to do things...)
public class StudentDriver
{
public static void main(String[ ] args)
{
//create an instance of Student
System.out.println("***** Creating a Student, calling the default constructor");
Student stud1 = new Student();
//print it so we can see what the default values were for the class data
//note that its toString() will be called automatically
System.out.println("\n***** printing it - notice the default values (set by Java)");
System.out.println(stud1);
//create another instance of a Student, passing in initial values to its constructor
System.out.println("\n***** Creating another Student, passing initial values to its constructor");
Student msBoss = new Student("Bill Gates", 56, 'm', 3.2, true);
//tell it to return its age
System.out.println("\n***** telling it to return its age.");
int theAge = msBoss.getAge();
System.out.println("Its age is: " + theAge);
//print it - note that its toString() will be called automatically;
System.out.println("\n***** printing it - see if values are correct");
System.out.println(msBoss);
//ask it if it is on probation
System.out.println("\n***** asking it if it is on probation (check answer)");
System.out.println("onProbation() returned: " + msBoss.onProbation());
//tell it to change its gpa to 1.3
System.out.println("\n***** telling it to change its gpa to 1.3");
msBoss.setGPA(1.3);
//print it now
System.out.println("\n***** printing it - see if the values are correct");
System.out.println(msBoss);
//ask it if it is on probation now
System.out.println("\n***** asking it if it is on probation (check answer)");
boolean boolAnswer = msBoss.onProbation();
System.out.println("onProbation() returned: " + boolAnswer);
//tell it to complain
System.out.println("\n***** telling it to complain");
System.out.println("complain() returned: " + msBoss.complain());
//tell it to change its onScholarship field to false
System.out.println("\n***** telling it to change its onScholarship field to false");
msBoss.setOnScholarship(false);
//print it now
System.out.println("\n***** printing it - see if the values are correct");
System.out.println(msBoss);
//ask it if it is on probation now
System.out.println("\n***** asking it if it is on probation (check answer)");
boolAnswer = msBoss.onProbation();
System.out.println("onProbation() returned: " + boolAnswer);
//create a different student, tell it to have some different values, and tell it to print itself
System.out.println("\n***** creating a different Student, passing initial values to its constructor");
Student stud2;
stud2 = new Student("Hillary Clinton", 64, 'f', 2.0, true); //notice-can define variable and create it in 2 steps
//print it
System.out.println("\n***** printing it - see if the values are correct");
System.out.println(stud2);
//ask it if it is on probation now
System.out.println("\n***** asking it if it is on probation (check answer)");
boolAnswer = stud2.onProbation();
System.out.println("onProbation() returned: " + boolAnswer);
}
}
Here is the class that I am writing.
public class Student
{
private String name;
private int age;
private char gender;
private double gpa;
private boolean onScholarship;
public Student()
{
}
public Student(String newName, int newAge, char newGender, double newGPA, boolean newScholarship)
{
this.name = newName;
this.age = newAge;
this.gender = newGender;
this.gpa = newGPA;
this.onScholarship = newScholarship;
}
public int getAge(int newAge)
{
return age;
}
public double setGPA (double newGPA)
{
this.setGPA = newGPA;
}
public boolean setOnScholarship (boolean newScholarship)
{
this.setOnScholarship = newScholarship;
}
public String toString()
{
return this.name + "\t" + this.age + "\t" + this.gender + "\t" + this.setGPA + "\t" + this.setOnScholarship;
}
public boolean onProbation()
{
if (onScholarship==true && gpa < 2.0)
return true;
else
return false;
}
}
Try to change this line:
this.setGPA = newGPA;
to this:
this.gpa = newGPA;
setGPA symbol not found is because there is no setGPA field (it is a method). You are trying to change the gpa field.
You also don't need the empty public Student() {} constructor -- this is automatically created by Java.
Also, as #Sam pointed out, since setOnScholarship() doesn't return anything, you can change the return type boolean to void. This is because there is no return statement, and this returning of nothing is a void type.
Overall, though, you have a good understanding on creating instances of another class (i.e., creating Students).
On request (although it doesn't have much to do with your code), here is a brief summary on static.
The static keyword is used with methods and fields that are not used with an instance of that class, but the class itself.
For example, in your case, pretty much all of the Student fields and methods are non-static, because they are properties of Student objects:
this.gpa;
this.setGpa();
On the other hand, if it were not changing a variable related to a single object, for example the total number of students, you could create a static field in Student:
public class Student {
// non-static fields for each instance
public double gpa;
// static field for the class
public static numStudents;
public Student() {
// create student by setting object (non-static) fields, for example...
this.gpa = 3.2;
// edit static variable
numStudents++; // notice how there is no `this` keyword - this changes a static variable
}
}
... and from StudentDriver, numStudents can be retreived with:
Student.numStudents; // notice how this is like `this.[property]`, but with the class name (Student) - it is an instance of the class
I hope this helps! OOP programming is a difficult topic that can't be explained so simply.
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..
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;
}