HashSet in java - java

I am studying programming using Java, and I facing a problem with java.util.HashSet. How to show the size() in HashSet? This my code?
package name;
public class Student
{
private String name;
public String getName()
{
return this.name;
}
public void setName(String name)
{
this.name = name;
}
}
// Entry Point
package client;
import name.Student;
import java.util.Set;
import java.util.HashSet;
import java.util.Scanner;
public class Client1
{
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
Set<Student> students = new HashSet<Student>();
Student student = new Student();
int totalStudent = 0;
System.out.print("TypeTotal Student : ");
totalStudent = Integer.parseInt(scan.nextLine());
for(int i = 0; i < totalStudent ; i++)
{
System.out.print("Name : ");
String name = scan.nextLine();
student.setName(name);
students.add(student);
}
System.out.println("Element Total In Set :" students.size());
for(Student std: students)
{
System.out.println(std.getName());
}
}
}
If I run this code in terminal, student.size() is not increasing.
I need advice.

That's because you're adding the same student everytime in hashset. And HashSet doesn't allow duplicate values.
Try this way.
// class Student
package name;
public class Student
{
private String name;
public String getName()
{
return this.name;
}
public void setName(String name)
{
this.name = name;
}
}
// Entry Point
package client;
import name.Student;
import java.util.Set;
import java.util.HashSet;
import java.util.Scanner;
public class Client1
{
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
Set<Student> students = null;
students = new HashSet<Student>();
Student student;
int totalStudent = 0;
System.out.print("TypeTotal Student : ");
totalStudent = Integer.parseInt(scan.nextLine());
for(int i = 0; i < totalStudent ; i++)
{
System.out.print("Name : ");
String name = scan.nextLine();
student = new Student();
student.setName(name);
students.add(student);
}
System.out.println("Element Total In Set :" students.size());
for(Student std: students)
{
System.out.println(std.getName());
}
}
}

In your code,
Student student is a reference to exactly one object (ever).
Since you do not allocate a new
Student each time you add an object to the students set,
you are,
instead,
adding the same object to the Set multiple times.
Note that I used the words "same object" and "Set".
A Set allows no more than one instance of an object.
Your code is pretending to add multiple students,
but is actually only adding one student.
The solution is as follows:
// really add a student to the set.
System.out.print("Name : ");
String name = scan.nextLine();
student = new Student();// note this line.
student.setName(name);
students.add(student);

If you use this block:
{
System.out.print("Name : ");
String name = scan.nextLine();
student.setName(name);
students.add(student);
}
you are using always same object and Hashset does not allow duplicate (even if you change one property of the object).
Using this block it works fine, because you are creating a new object every interaction:
{
System.out.print("Name : ");
String name = scan.nextLine();
student = new Student();
student.setName(name);
students.add(student);
}
even if the variable is the same (student) you create a new instance with new

Related

How to make a new instance of an object that doesn't overwrite the existing one?

So, I've got some homework to do and I made a simple user input application that at the end outputs (I want that I do that) all inputs that were typed. The problem is I don't know how to make it that it doesn't overwrite the existing object but that it makes a new one.
I presume that I can make an array or something like that and it should resolve the problem, but it doesn't resolve my question, so I came here for help.
public class Main {
public static void main(String[] args) {
String next ="y";
int studentNum = 1;
Scanner scanner = new Scanner(System.in);
System.out.println("Do you want to add a student? y/n");
if(scanner.nextLine().equalsIgnoreCase("n"))
System.exit(0);
for(int i = 0;i<studentNum;i++){
Student student = new Student();
System.out.println("ID: ");
student.setId(scanner.nextLine());
System.out.println(("Ime: "));
student.setName(scanner.nextLine());
System.out.println("Prezime: ");
student.setSurname(scanner.nextLine());
System.out.println("Do you want to add another student? y/n");
if(scanner.nextLine().equalsIgnoreCase("y"))
studentNum+=1;
else
for(i =0;i<studentNum;i++)
System.out.println(student.toString());
}
}
And the Student Class
public class Student {
#Override
public String toString() {
return String.format("ID: %s \n%s %s\nAverage grade %.2f\n____________________\n",
id, surname, name, averageGrade() );
}
#Override
public boolean equals(Object obj) {
// pretpostavljamo da je predani objekt iz klase Student
Student otherStudent = (Student) obj;
return id.equals(otherStudent.id);
}
final int ARR_SIZE = 60;
private String id;
private String name;
private String surname;
private int noOfGrades;
private CourseGrade[] grades;
public String getId() {
return id;
}
public void setId(String newId) {
id = newId;
}
public String getName() {
return name;
}
public void setName(String newName) {
name = newName;
}
public String getSurname() {
return surname;
}
public void setSurname(String newSurname) {
surname = newSurname;
}
If I want to add another student it overwrites the existing one, which I expected, but I don't know how to make it that it makes a new instance.
Here is example code of how to use a List to store several students:
import java.util.List;
import java.util.ArrayList;
..
List<Student> students = new ArrayList<Student>();
Student s = new Student();
s.setName("Joe");
students.add(s);
Student t = new Student();
t.setName("Jack");
students.add(t);
for(Student student : students) {
System.out.println(student.toString());
}
With this information, you should be able to finish your work.

How to check if a substring is present in a string which is part of an ArrayList

So I'm adding Students (which are objects) to my arrayList and in the beginning of the code I'll let the user add as many students + studentnumbers until they enter blank. Once they entered blank my program prints out all the students and their studentnumber. Once it printed out the students and their number the user is asked to give a search term. Then the program will print out all the students which have said search term. Everything in my code works apart from comparing the search term with the strings in my ArrayList
This is what I came up with so far:
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
ArrayList<Student> students = new ArrayList<Student>();
System.out.print("name: ");
String name = reader.nextLine();
while (!name.equals("")) {
System.out.print("studentnumber: ");
String studentNumber = reader.nextLine();
students.add(new Student(name, studentNumber));
System.out.print("name: ");
name = reader.nextLine();
}
for (Student prs : students ) {
System.out.println(prs);
}
System.out.println("Give search term: ");
String searchTerm = reader.nextLine();
System.out.println("Result: ");
for (Student prs : students) {
if (prs.contains(searchTerm)) {
System.out.println(prs);
}
}
}
}
So my question is how I can fix the code line
for (Student prs : students) {
if (prs.contains(searchTerm)) {
System.out.println(prs);
}
}
to make it work.
Thank you for your assistance.
Modify your student class like this no need to change other code,just look it into custom contains method
package com.tried;
public class Student {
String name;
String studentNumber;
public Student(String name2, String studentNumber) {
this.name=name2;
this.studentNumber=studentNumber;
// TODO Auto-generated constructor stub
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStudentNumber() {
return studentNumber;
}
public void setStudentNumber(String studentNumber) {
this.studentNumber = studentNumber;
}
public boolean contains(String term){
System.out.println(this.studentNumber+"and"+this.name);
if(this.studentNumber.contains(term) || this.name.contains(term)){
return true;
}
return false;
}
#Override
public String toString() {
return "Student [name=" + name + ", studentNumber=" + studentNumber + "]";
}
}
Assuming you overrode the toString method of Student class properly, change
for (Student prs : students) {
if (prs.contains(searchTerm)) {
System.out.println(prs);
}
with
for (Student prs : students) {
if (prs.toString().contains(searchTerm)) {
System.out.println(prs);
}

How to create a search method for an array

My code is as follows:
import java.io.*;
import java.util.*;
public class readStudents extends Object
{
private String SName = "";
private String DoB = "";
private String Gender = "";
private String Address = "";
Student [] students = new Student[20];
public void fillStudentArray()
{
// properties
int size; // total number of Students in collection
File file = new File("StudentDetails.txt");
try
{
Scanner in = new Scanner(file);
while(in.hasNextLine())
{
String SName = in.next();
String DoB = in.next();
String Gender = in.next();
String Address = in.next();
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
public String getName()
{
return this.SName;
}
public void printname()
{
System.out.println("hello");
}
public Student search(String name)
{
System.out.print("Enter the name you wish to search: ");
for (int i = 0; i < this.students.length; i++)
{
Student s = this.students[i];
if (s.getName().equalsIgnoreCase(name))
{
return s;
}
}
return null;
}
} //end class students
However I am trying to create a well refined program that I can call on these methods from another main file with as minimal code as possible in that file.
The search method at the bottom is tripping me up as I am assuming I need to put something to do with the array in my getName() method but I can't figure it out.
Since I am doing this as a class for another main method, with the placement of my array initialization and declaration it allows the other methods to access it but it leaves me with no way to create this array from the main method unless I am missing something?
This is the error jCreator is throwing:
F:\University\Ass2\readStudents.java:62: error: cannot find symbol
if (s.getName().equalsIgnoreCase(name))
^
symbol: method getName()
location: variable s of type Student
You never populated the Student students[] array... You retrieved the values you would populate them with here:
while(in.hasNextLine())
{
String SName = in.next();
String DoB = in.next();
String Gender = in.next();
String Address = in.next();
}
But you never actually set those values into a Student object in the students[] array
Do something like this:
int i = 0;
while(in.hasNextLine())
{
String name = in.next();
String dateOfBirth = in.next();
String gender = in.next();
String address = in.next();
students[i] = new Student(name, dateOfBirth, gender, address);
i++
}
Also, you might consider ditching the array and using some sort of List or Hash object... If your file contains more than 20 lines, the array will be out of index when you try to define the 21st value.. With an arraylist or a List you wouldn't have that problem
I took a liberty to tweak your code as previous answer mentioned, it's better to use array list in your case. You could make a small student container class within your reader. The get name method is also kinda redundant ;s
package test;
import java.io.*;
import java.util.*;
public class readStudents{
ArrayList<Student> students = new ArrayList<Student>();
class Student {
private String name;
private String dob;
private String gender;
private String address;
public Student(String name, String dob, String gender, String address) {
this.name = name;
this.dob = dob;
this.gender = gender;
this.address = address;
}
public void fillStudentArray() {
// properties
int size; // total number of Students in collection
File file = new File("StudentDetails.txt");
try {
Scanner in = new Scanner(file);
while (in.hasNextLine()) {
String SName = in.next();
String DoB = in.next();
String Gender = in.next();
String Address = in.next();
students.add(new Student(SName, DoB, Gender, Address));
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public String getName(Student student) {
return student.name;
}
public void printname() {
System.out.println("hello");
}
public Student search(String name) {
System.out.print("Enter the name you wish to search: ");
for (Student student : students) {
if (student.name.equalsIgnoreCase(name))
;
return student;
}
return null;
}
}
}
If you're not forced by your teacher to use for or for-each cycle in the search function - this is how to do a full scan the Java 8 way
public Optional<Student> findFirstByName(final String name) {
return Arrays.stream(students)
.filter(s -> s.getName().equalsIgnoreCase(name))
.findFirst();
}

String ArrayList returning null values

I am new to java and doing some arraylist work, and when compiling my lists just return null values instead of names I have typed in.
I don't understand why this is so, so if anyone could advise/help me that would be great.
Here is my main code
import java.util.*;
public class StudentData
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
ArrayList<Student> studentList = new ArrayList<Student>();
String yesNo = "true";
do
{
System.out.println("Enter student's name: ");
String name = in.next();
Student s = new Student();
studentList.add(s);
String input;
do
{
System.out.println("Would you like to enter data for another student? Yes/No ");
yesNo = in.next();
}
while (!yesNo.equalsIgnoreCase("YES") && !yesNo.equalsIgnoreCase("NO"));
}
while (yesNo.equalsIgnoreCase("YES"));
for(int i = 0; i < studentList.size(); i++)
{
System.out.println(studentList.get(i).getName());
}
}
}
And
class Student
{
private String studentName;
public StudentData(String name)
{
setName(name);
}
public String getName()
{
return studentName;
}
public void setName(String name)
{
studentName = name;
}
}
You're creating a student but didn't set the name :
String name = in.next();
Student s = new Student();
studentList.add(s);
Try with :
String name = in.next();
Student s = new Student();
s.setName(name);
studentList.add(s);
Also replace your constructor. I.e :
public StudentData(String name){
setName(name);
}
should be
public Student(String name) {
setName(name);
}
Then you will be able to do Student s = new Student(name);

Class Constructor Problems While Doing A Linear Search Across Two Classes

Im creating a program that is supposed have the user enter a student name and see if it exist in the student array using a linear search method. The student array is in a different class and im having trouble creating a constructor i have tried many things and its not working can someone point me in the right direction.
My linear search class is
import java.util.*;
import java.util.Scanner;
public class LinearSearch {
public int find(Student [] a, String nm) {
for (int i = 0; i < a.length; i++) {
if (a[i].equals(nm)){
return i;
break;
}
else{
return -1;
}
}
}
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
LinearSearch search = new LinearSearch();
Student stu = new Student();
Student [] arr = stu.getArray();
System.out.print("Enter the name to search: ");
String name = reader.nextLine();
int n = search.find(arr, name);
if ((n >= 0) && (n < arr.length)) {
System.out.println(name + " was found at index: " + n);
} else {
System.out.println(name + " was not found");
}
}
}
My Student class is
import java.util.*;
public class Student {
public Student(){
}
public Student [] getArray(){
Student [] studentArray = new Student[3];
studentArray[0] = new Student ("Mel");
studentArray[1] = new Student ("Jared");
studentArray[2] = new Student ("Mikey");
return studentArray;
}
}
You defined a constructor with no argument:
public Student() {
}
But you're invoking a constructor which needs a String as argument:
studentArray[0] = new Student("Mel");
So, your constructor should have a String as argument:
public Student(String name)
And you should probably store this name as a field in the Student class:
private String name;
public Student(String name) {
this.name = name;
}
Note that there is no way that a Student instance could be equal to a String instance. You should provide a getter method for the name, and compare the entered String with the name of the student, instead of comparing it with the student itself.
import java.util.*;
public class Student {
private String name;
public Student(String name){
this.name = name;
}
public Student [] getArray(){
Student [] studentArray = new Student[3];
studentArray[0] = new Student ("Mel");
studentArray[1] = new Student ("Jared");
studentArray[2] = new Student ("Mikey");
return studentArray;
}
public String getName(){
return name;
}
}
and of course in the compersion you'll need to do:
f (a[i].getName().equals(nm)){
public class Student {
private String studentName;
private Student[] studentArray;
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public Student[] getStudentArray() {
return studentArray;
}
public void setStudentArray(Student[] studentArray) {
this.studentArray = studentArray;
}
public Student(){
studentArray = new Student[3];
}
public Student[] getArray() {
Student st1 = new Student();
st1.setStudentName("mel");
Student st2 = new Student();
st2.setStudentName("Jared");
Student st3 = new Student();
st3.setStudentName("Mikey");
studentArray[0]=st1;
studentArray[1]=st2;
studentArray[2]=st3;
return studentArray;
}
}
the above code is your Student class. there is no need to create a constructor though. but because you would like it i put it in the code.
the LinearSearch class is as follow:
public class LinearSearch {
private int i;
public int find(Student[] a, String nm) {
for ( i = 0; i < a.length; i++) {
if (a[i].getStudentName().equals(nm)) {
break;
} else {
i = -1;
}
}
return i;
}
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
LinearSearch search = new LinearSearch();
Student stu = new Student();
Student[] arr = stu.getArray();
System.out.print("Enter the name to search: ");
String name = reader.nextLine();
int n = search.find(arr, name);
if ((n >= 0) && (n < arr.length)) {
System.out.println(name + " was found at index: " + n);
} else {
System.out.println(name + " was not found");
}
}
}

Categories