Apologies for the poor title but I don't know how to phrase my issue. I am attempting to call the getSSN method from the Student class in my BubbleSorter class after a few students have been placed in an ArrayList. How can I call for the specific SSN variable. I understand why the error is occuring, but not how to change it to make it work. The error message is as follows: The method getSSN() is undefined for the type SearchandSort.
My Student Class:
public class Student {
private String firstName, lastName;
private int SSN;
public Student(String first, String last, int ssn) {
firstName = first;
lastName = last;
SSN = ssn;
}
public String toString() {
return lastName + ", " + firstName + " " + SSN + "\t";
}
public boolean equals(Object other) {
return (lastName.equals(((Student)other).getLastName()) && firstName.equals(((Student)other).getFirstName()) && (SSN == (((Student)other).getSSN())));
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName (String lastName) {
this.lastName = lastName;
}
public int getSSN() {
return SSN;
}
public void setSSN(int SSN) {
this.SSN = SSN;
}
}
My BubbleSorter:
import java.lang.reflect.Array;
// “On my honor, I have neither received nor given any unauthorized assistance on this examination.”
public class BubbleSorter {
public static void bubbleSort(SortandSearch Students[]) {
int lastPos;
int index;
int temp;
for (lastPos = Students.length-1; lastPos >= 0; lastPos--) {
for (index = 0; index <= lastPos - 1; index++) {
if (((Students[index]).getSSN()) - ((Students[index+1].getSSN())) > 0) {
temp = Students[index].getSSN();
Students[index].getSSN() = Students[index+1].getSSN();
Students[index+1].getSSN() = temp;
}
}
}
}
}
My main class:
import java.util.ArrayList;
import java.util.Scanner;
public class SortandSearch {
public static void main(String[] args) {
Student a = new Student("Ryan", "Jones", 123456);
Student b = new Student("Jolie", "Decker", 123457);
ArrayList<Student> Students = new ArrayList<Student>();
Students.add(a);
Students.add(b);
System.out.println(Students);
bubbleSort(Students);
System.out.println(Students);
System.out.println("Please enter the SSN of the student you are searching for:");
Scanner scan = new Scanner(System.in);
int searchKey = scan.nextInt();
for (int index = 0; index < Students.size(); index++) {
if (Students.get(index).getSSN() == searchKey) {
System.out.print("The student with SSN " + searchKey + " is located at " + index);
}
}
}
}
EDIT:
The error now shows: The type of the expression must be an array type but it resolved to ArrayList.
New BubbleSorter:
import java.util.ArrayList;
// “On my honor, I have neither received nor given any unauthorized assistance on this examination.”
public class BubbleSorter {
public static void bubbleSort(ArrayList<Student> studentList) {
int lastPos;
int index;
int temp;
for (lastPos = studentList.size()-1; lastPos >= 0; lastPos--) {
for (index = 0; index <= lastPos - 1; index++) {
if ((studentList.get(index).getSSN()) - ((studentList.get(index).getSSN())) > 0) {
temp = studentList[index];
studentList[index] = studentList[index+1];
studentList[index+1] = temp;
}
}
}
}
}
There seem multiple things wrong to this code. I think you are trying unnessecary casting your arraylist to something else
First, I think your function signature should change to
public static void bubbleSort(ArrayList<Student> studentList)
And then you can access the elements with:
studentList.get(index).getSSN()
In SortandSearch you put instances of Student into ArrayList<>, and the your bubbleSort method must also take argument of this type or at least List and then convert it to array and return sorted list:
public static List<Student> bubbleSort(List<Student> studentsList) {
Student[] Students = studentsList.toArray(new Student[studentsList.size()]);
// ...
return Arrays.asList(Students);
}
And in the calling main method you need to store sorted list:
List<Student> sorted = BubbleSorter.bubbleSort(Students);
System.out.println(sorted);
Related
I am new in java and I trying to get information
for five students and save them into an array of classes. how can I do this?
I want to use class person for five students whit different informations
import java.io.IOException;
import java.util.*;
public class exam
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
// I want to get and save information in this array
person[] f = new student[5];
}
}
class person defined for get name and family name.
import java.util.*;
public abstract class person {
Scanner scr = new Scanner(System.in);
private String name , fname;
public void SetName() {
System.out.println("enter name and familyNAme :");
name = scr.next();
}
public String getname() {
return name;
}
public void setfname () {
System.out.println("enter familyname:");
fname = scr.next();
}
public String getfname() {
return fname;
}
}
class student that inherits from the class person for get studentID and student Scores .
import java.util.*;
class student extends person {
float[] p = new float[5];
int id , sum ;
float min;
public void inputs() {
System.out.println("enter the id :");
id = scr.nextInt();
}
public void sumation() {
System.out.println("enter points of student:");
sum= 0;
for(int i = 0 ; i<5 ; i++){
p[i]=scr.nextFloat();
sum+=p[i];
}
}
public void miangin() {
min = (float)sum/4;
}
}
So first things first, when creating Java objects, refrain from getting input inside the object so that if you decide to change the way you get input (e.g. transition from command line to GUI) you don't need to modify the Java object.
Second, getters and setters should only get or set. This would save some confusion when debugging since we don't have to check these methods/functions.
So here's the person object:
public abstract class Person {
protected String name, fname;
public Person (String name, String fname) {
this.name = name;
this.fname = fname;
}
public void setName (String name) {
this.name = name;
}
public String getName () {
return name;
}
public void setFname (String fname) {
this.fname = fname;
}
public String getFname () {
return fname;
}
}
And here's the student object (tip: you can make as much constructors as you want to make object creation easier for you):
public class Student extends Person {
private float[] p;
private int id;
public Student (String name, String fname) {
this (name, fname, -1, null);
}
public Student (String name, String fname, int id, float[] p) {
super (name, fname);
this.id = id;
this.p = p;
}
public void setP (float[] p) {
this.p = p;
}
public float[] getP () {
return p;
}
public void setId (int id) {
this.id = id;
}
public int getId () {
return id;
}
public float summation () {
float sum = 0;
for (int i = 0; i < p.length; i++)
sum += p[i];
return sum;
}
public float miangin () {
return summation () / 4.0f;
}
#Override
public String toString () {
return new StringBuilder ()
.append ("Name: ").append (name)
.append (" Family name: ").append (fname)
.append (" Id: ").append (id)
.append (" min: ").append (miangin ())
.toString ();
}
}
And lastly, wherever your main method is, that is where you should get input from. Take note that when you make an array, each index is initialized to null so you still need to instantiate each array index before using. I made a sample below but you can modify it depending on what you need.
import java.util.*;
public class Exam {
Scanner sc;
Person[] people;
Exam () {
sc = new Scanner (System.in);
people = new Person[5];
}
public void getInput () {
for (int i = 0; i < people.length; i++) {
System.out.print ("Enter name: ");
String name = sc.nextLine ();
System.out.print ("Enter family name: ");
String fname = sc.nextLine ();
System.out.print ("Enter id: ");
int id = sc.nextInt (); sc.nextLine ();
System.out.println ("Enter points: ");
float[] points = new float[5];
for (int j = 0; j < points.length; j++) {
System.out.printf ("[%d] ", j + 1);
points[j] = sc.nextFloat (); sc.nextLine ();
}
people[i] = new Student (name, fname, id, points);
}
}
public void printInput () {
for (Person p: people)
System.out.println (p);
}
public void run () {
getInput ();
printInput ();
}
public static void main (String[] args) {
new Exam ().run ();
}
}
Just one last tip, if you ever need dynamic arrays in Java, check out ArrayList.
You can add a class attribute, and then add class information for each student, or you can add a class class, define an array of students in the class class, and add an add student attribute, and you can add students to that class.
First of all, please write class names with capital letter (Student, Exam <...>).
Exam class:
import java.util.Scanner;
public class Exam {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Student[] students = new Student[]{
new Student(),
new Student(),
new Student(),
new Student(),
new Student()
};
for (int i = 0; i < 5; i++) {
students[i].setFirstName();
students[i].setLastName();
students[i].setId();
}
}
}
Person class:
import java.util.Scanner;
public class Person {
String firstName, lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName() {
System.out.println("Type firstName: ");
this.firstName = new Scanner(System.in).next();
}
public String getLastName() {
return lastName;
}
public void setLastName() {
System.out.println("Type lastName: ");
this.lastName = new Scanner(System.in).next();
}
}
Student class:
import java.util.Scanner;
public class Student extends Person{
int id;
public int getId() {
return id;
}
public void setId() {
//Converting String line into Integer by Integer.parseInt(String s)
System.out.println("Type id: ");
this.id = Integer.parseInt(new Scanner(System.in).next());
}
}
Alright I am stuck on how do I implement this binary search that will receive data from other classes.
I am trying to implement it in my own ADT.
I have implemented a List ADT manually but now I want to add in a search operation which utilizes binary search algorithm manually and doesn't uses any built in Java API.
Example this is my sorted list interface that I implemented manually.
public class SortedArrayList<T extends Comparable<T>> implements SortedListInterface<T>{
private boolean binarySearch(// What parameters should I receive from Student Object?) {
// This will be my binary search implementation
}
}
The problem is I will be creating a Student class where I will add the instances of the student class into the sortedArrayList above.
Like how am I going to receive the data to be put into the binary search algorithm in a generics typed sortedArrayList?
Do note I am not allowed to use any JAVA Built-IN API , everything must be implemented manually else I can finish this easily but its a pain now since its limited.
Example I want to binary search by Student name from Student's class. How will I need to implement and receive data into this manually implemented ADT of mine?
public class SortedArrayList<T extends Comparable<T>> implements SortedListInterface<T>{
private T[] list;
private boolean binarySearch(int first, int last, T desiredItem) {
int mid = (first + last) / 2;
if(desiredItem.getFullName().equals(list[mid])
// This part over here. How do I access attributes from Student class in this ADT so that I can access the data and do comparison for the binary search..
}
}
How do I access attributes from Student class into my own ADT so that I can do comparisons on binary search algorithm?!
I am literally stuck.
I would appreciate someone giving me directions.
I repeat again no BUILT-IN APIs from JAVA, implementation manually only
ADT SortedList Interface
public interface SortedListInterface <T extends Comparable<T>> {
public boolean add(T element);
public T get(int index);
public boolean search(T element);
public T remove(int index);
public void clear();
public int getLength();
public boolean isEmpty();
public boolean isFull();
}
ADT SortedList Implementation Code
public class SortedArrayList<T extends Comparable<T>> implements SortedListInterface<T>{
//Data Types
private T[] list;
private int length;
private static final int SIZE = 10;
// Constructors
public SortedArrayList() {
this(SIZE);
}
public SortedArrayList(int size) {
length = 0;
list = (T[]) new Comparable[SIZE]; // an array of instances of a class implementing Comparable interface and able to use compareto method but its overidden instead
}
// Setter & Getters
#Override
public int getLength() {
return length;
}
#Override
public boolean isEmpty() {
return length == 0;
}
#Override
public boolean isFull() {
return false;
}
#Override
public void clear() {
length = 0;
}
// Array Expansion
private boolean isArrayFull() {
return length == list.length;
}
private void expandArray() {
T[] oldList = list;
int oldSize = oldList.length;
list = (T[]) new Object[2 * oldSize];
for (int i = 0; i < oldSize; i++) // copy old array elements into new array elements
list[i] = oldList[i];
}
// ADT METHODs
// Add New Elements Function
#Override
public boolean add(T element) {
int i = 0;
while (i < length && element.compareTo(list[i]) > 0) // return 0 with equal , return more than 1 if element larger than list[i] , return -1 if less
i++;
makeRoom(i + 1);
list[i] = element;
length++;
return true;
}
private void makeRoom(int index) { // accepts given index
int newIndex = index - 1;
int lastIndex = length - 1;
for (int i = lastIndex; i >= newIndex; i--)
list[i + 1] = list[i];
}
//Remove Elements Function
#Override
public T remove(int index) { // accepts given index
T result = null;
if ( index >= 1 && index <= length ) {
result = list[index - 1];
if (index < length)
removeGap(index);
length--;
}
return result;
}
private void removeGap(int index) { // accepts given index and remove the gap where the element its removed
int removedIndex = index - 1;
int lastIndex = length - 1;
for (int i = removedIndex; i < lastIndex; i++)
list[i] = list[i + 1]; // shifts elements back to remove the gap
}
// Get Element
#Override
public T get(int index) { // accepts given index and return the object
T object = null;
if ( index >= 1 && index <= length)
object = list[index - 1];
return object;
}
// Search Algorithms
#Override
public boolean search(T element) {
return binarySearch(element);
}
private boolean binarySearch(// Implementation here) {
// Implementation here
}
//To String Method
#Override
public String toString() {
String result = "";
for (int i = 0; i < length; i++)
result += list[i] + "\n";
return result;
}
}
Student Class Implementation
public class Student implements Comparable<Student>{
// Data Types
private Name name;
private char gender;
private String icNo;
private String mobileNo;
private Course course;
private int group;
private String dOB;
// Constructors
public Student() {
}
public Student(Name name, char gender, String icNo, String mobileNo, Course course, int group, String dOB) {
this.name = name;
this.gender = gender;
this.icNo = icNo;
this.mobileNo = mobileNo;
this.course = course;
this.group = group;
this.dOB = dOB;
}
public Student(Name name) {
this.name = name;
}
// setter
public void setName(Name name) {
this.name = name;
}
public void setGender(char gender) {
this.gender = gender;
}
public void setIcNo(String icNo) {
this.icNo = icNo;
}
public void setMobileNo(String mobileNo) {
this.mobileNo = mobileNo;
}
public void setCourse(Course course) {
this.course = course;
}
public void setGroup(int group) {
this.group = group;
}
public void setdOB(String dOB) {
this.dOB = dOB;
}
// getter
public Name getName() {
return name;
}
public char getGender() {
return gender;
}
public String getIcNo() {
return icNo;
}
public String getMobileNo() {
return mobileNo;
}
public Course getCourse() {
return course;
}
public int getGroup() {
return group;
}
public String getdOB() {
return dOB;
}
#Override
public String toString() {
return "Student{" + "name=" + name + ", gender=" + gender + ", icNo=" + icNo + ", mobileNo=" + mobileNo + ", course=" + course + ", group=" + group + ", dOB=" + dOB + '}';
}
public int compareTo(Student object) { // Sort according to name if name same then sort according to gender and so on.
int c = this.name.getFullName().compareTo(object.getName().getFullName());
if(c == 0)
c = this.gender - object.getGender();
if(c == 0)
c = this.icNo.compareTo(object.getIcNo());
if(c == 0)
c = this.mobileNo.compareTo(object.getMobileNo());
if(c == 0)
c = this.group - object.getGroup();
if(c == 0)
c = this.dOB.compareTo(object.getdOB());
return c;
}
}
Course Class
public class Course {
// Data Types
private String courseCode;
private String courseName;
private double courseFee;
// Constructors
public Course() {
}
public Course(String courseCode, String courseName, double courseFee) {
this.courseCode = courseCode;
this.courseName = courseName;
this.courseFee = courseFee;
}
// setter
public void setCourseCode(String courseCode) {
this.courseCode = courseCode;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public void setCourseFee(double courseFee) {
this.courseFee = courseFee;
}
// getter
public String getCourseCode() {
return courseCode;
}
public String getCourseName() {
return courseName;
}
public double getCourseFee() {
return courseFee;
}
#Override
public String toString() {
return "CourseCode = " + courseCode + "Course Name = " + courseName + "Course Fee = " + courseFee;
}
}
Name Class
public class Name {
// Data Types
private String firstName;
private String lastName;
// Constructors
public Name() {
}
public Name(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
// setter
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
// getter
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getFullName(){
return firstName + " " + lastName;
}
#Override
public String toString() {
return "Name{" + "firstName=" + firstName + ", lastName=" + lastName + '}';
}
The binary search algorithm relies on comparing a value being searched for with values in the list being searched. That's why the declaration of your class that implements the SortedListInterface is:
SortedArrayList<T extends Comparable<T>>
Note the extends Comparable<T>.
Comparable is an interface through which you can compare two objects. Hence in the search() method that you have to implement, you know that every object in the list defines the compareTo() method and you simply use that method to compare the object being searched for with individual objects in the list.
Here is a simple implementation of the binary search algorithm in the context of your project.
private T[] list; // The list to search.
private int count; // The number of non-null elements in 'list'.
public boolean search(T element) {
boolean found = false;
int lo = 0;
int hi = count - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (list[mid].compareTo(element) < 0) {
lo = mid + 1;
}
else if (list[mid].compareTo(element) > 0) {
hi = mid - 1;
}
else {
found = true;
break;
}
}
return found;
}
With a method, you have a method parameter. In the method code you use the parameter name. But when you invoke that method from other code, you provide a value which is substituted for the parameter. In the same way, the code above uses a type parameter which is substituted with the name of an actual class when you create an instance of class SortedArrayList. In your case, T is substituted with Student and class Student must implement the compareTo() method. Hence method search(), in class SortedArrayList does not need to know about the members in class Student.
So you would first create an instance of SortedArrayList like this:
SortedArrayList<Student> theList = new SortedArrayList<>();
Then you can call the search() method like this:
Student s = new Student(/* relevant parameter values */);
theList.search(s);
EDIT
I understand that you don't necessarily want to search for a Student, you may want to search for the Name of a student or a student's mobile phone number. In that case I believe you need a Comparator. Here is the code for class SortedArrayList with the addition of a Comparator
import java.util.Comparator;
import java.util.Objects;
public class SortedArrayList<T extends Comparable<T>> implements SortedListInterface<T> {
private static final int SIZE = 10;
private Comparator<? super T> comparator;
private T[] list;
private int count;
#SuppressWarnings("unchecked")
public SortedArrayList(Comparator<? super T> c) {
comparator = c;
list = (T[]) new Comparable[SIZE]; // No way to verify that 'list' only contains instances of 'T'.
/* NOTE: Following is not allowed.
list = new T[SIZE]; // Cannot create a generic array of T
*/
}
#Override
public boolean add(T element) {
Objects.requireNonNull(element, "Cannot add null element.");
boolean result = false;
if (count == 0) {
list[0] = element;
count = 1;
result = true;
}
else {
if (!isFull()) {
int i = 0;
while (list[i] != null) {
if (element.compareTo(list[i]) < 0) {
break;
}
i++;
}
if (list[i] != null) {
for (int j = count - 1; j >= i; j--) {
list[j + 1] = list[j];
}
}
list[i] = element;
count++;
result = true;
}
}
return result;
}
#Override
public T get(int index) {
checkIndex(index);
return list[index];
}
#Override
public boolean search(T element) {
if (comparator == null) {
return binarySearchComparable(element);
}
else {
return binarySearchComparator(element);
}
}
#Override
public T remove(int index) {
checkIndex(index);
T removed = list[index];
list[index] = null;
for (int i = index; i < count; i++) {
list[i] = list[i + 1];
}
count--;
list[count] = null;
return removed;
}
#Override
public void clear() {
for (int i = 0; i < count; i++) {
list[i] = null;
}
count = 0;
}
#Override
public int getLength() {
return count;
}
#Override
public boolean isEmpty() {
return count == 0;
}
#Override
public boolean isFull() {
return count == SIZE;
}
private boolean binarySearchComparable(T element) {
boolean found = false;
int lo = 0;
int hi = count - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (list[mid].compareTo(element) < 0) {
lo = mid + 1;
}
else if (list[mid].compareTo(element) > 0) {
hi = mid - 1;
}
else {
found = true;
break;
}
}
return found;
}
private boolean binarySearchComparator(T key) {
int low = 0;
int high = count - 1;
while (low <= high) {
int mid = (low + high) >>> 1;
T midVal = list[mid];
int cmp = comparator.compare(midVal, key);
if (cmp < 0)
low = mid + 1;
else if (cmp > 0)
high = mid - 1;
else
return true; // key found
}
return false; // key not found.
}
private void checkIndex(int index) {
if (index < 0) {
throw new IllegalArgumentException("Negative index.");
}
if (index >= count) {
throw new IllegalArgumentException(String.format("Supplied index %d is not less than %d", index, count));
}
}
}
Here is an example Comparator for the Name of a Student
import java.util.Comparator;
public class NameComparator implements Comparator<Student> {
#Override
public int compare(Student student1, Student student2) {
int result;
if (student1 == null) {
if (student2 == null) {
result = 0;
}
else {
result = -1;
}
}
else {
if (student2 == null) {
result = 1;
}
else {
result = student1.getName().getFullName().compareTo(student2.getName().getFullName());
}
}
return result;
}
}
So in order to search the list according to any combination of Student attributes, simply implement an appropriate Comparator and pass it to the SortedArrayList class.
EDIT 2
Following your comments from November 17, 2019.
Below is code for a "name and mobile" Comparator. As I wrote in my previous Edit, you need to write an appropriate Comparator for a given combination of Student attributes.
import java.util.Comparator;
/**
* Compares {#code Student} name and mobile phone number.
*/
public class NameAndMobileComparator implements Comparator<Student> {
#Override
public int compare(Student student1, Student student2) {
int result;
if (student1 == null) {
if (student2 == null) {
result = 0;
}
else {
result = -1;
}
}
else {
if (student2 == null) {
result = 1;
}
else {
result = student1.getName().getFullName().compareTo(student2.getName().getFullName());
if (result == 0) {
result = student1.getMobileNo().compareTo(student2.getMobileNo());
}
}
}
return result;
}
}
I am trying to get my addStudent() method in the Roster class to work here.
It's supposed to add a given student to this roster. If the student is already on the roster, or the numStudents == stopPoint, it doesn't change the roster and returns false. If it is successful it returns true.
Roster Class:
public class Roster {
Student[] students;
int numStudents;
int stopPoint;
Course course;
//constructor for this class initialize this roster to empty
public Roster(int stopPoint, Course course)
{
this.stopPoint = stopPoint;
this.course = course;
}
//returns a string that represents the object for printing
public String toString()
{
String res = "";
for(int j = 0; j < numStudents; j++)
{
res = res + "\n" + students[j].toString();
}
return course + " " + numStudents + "/" + stopPoint+res;
}
//returns true if and only if the number of students in it is at stopPoint
public boolean isFull(int numStudents, int stopPoint)
{
if (numStudents == stopPoint)
{
return true;
}
else
return false;
}
/*add given student to this roster if student already on roster
or numStudents already == stopPoint, will not change roster and return
false but return true if successful, else false
*/
public boolean addStudent(Student student)
{
if(this.numStudents < this.stopPoint)
{
this.students[numStudents] = student; // here is where I get the error
this.numStudents++;
return true;
}
else
return false;
}
}
Testing Class:
public class TestRoster
{
public static void main(String[] args)
{
Student s1 = new Student("John","Doe");
Course c1 = new Course(198, 111);
Roster r1 = new Roster(4, c1);
System.out.println(r1);
testAdd(r1, s1);
}
private static void testAdd(Roster r, Student s)
{
System.out.println(s.familyName+" "+r.addStudent(s));
System.out.println(r);
}
}
Student Class:
public class Student
{
String personalName;
String familyName;
public Student(String pName, String fName)
{
personalName = pName;
familyName = fName;
}
public String toString( )
{
return "Student: " + familyName + ", "+ personalName;
}
}
Lastly, the Course Class:
public class Course
{
int deptNum;
int courseNum;
public Course(int deptNum, int courseNum)
{
this.deptNum = deptNum;
this.courseNum = courseNum;
}
public String toString( )
{
return deptNum + ":" + courseNum;
}
}
Here is the error:
Exception in thread "main" java.lang.NullPointerException
at assign4.Roster.addStudent(Roster.java:56)
at assign4.TestRoster.testAdd(TestRoster.java:17)
at assign4.TestRoster.main(TestRoster.java:13)
Java Result: 1`
The other answers suggest using an arbitrary number for the array instansiation, this is not a good idea as you never know if it will be enough.
Your Roster class knows how many students there should be (via the constructor), you should initialize the Student array with stopPoint:
Student[] students;
int numStudents;
int stopPoint;
Course course;
public Roster(int stopPoint, Course course)
{
this.stopPoint = stopPoint;
this.course = course;
this.students = new Student[this.stopPoint]
}
Since you can't touch your class variables, you can and should initialize the array within the constructor.
i have problem with printing the array after reading it. After printing, the address of memory is printed, not value of the array. What can i do for that ?
public class MyClass
{
Student St = new Student();
Student[]Array1 = new Student[10];
void AddList()
{
Scanner Scan = new Scanner(System.in);
for (int i=0; i<Array1.length & i<ArrayF1.length; i++)
{
System.out.println("Enter Student NAME Number " + (i+1) + ":");
Array1[i] = new Student();
Array1[i].setName(Scan.next());
//System.out.println("Enter Student MARK Number " + (i+1) + ":");
//St.setMark(Scan.nextFloat());
}
}
this is my print method. The result of print is like this
(studentproject.Student#1a758cb)
void PrintList()
{
for (int i=0; i<Array1.length; i++)
{
System.out.println(Array1[i]);
}
}
this is my Student Class that i have all my setter and getter method on that ... So i have 3 Class how can i work with this 3 class and in one of them get the data and in another print the Mark data and in third class print the Student Name data ... how can i do that ... i do some code but i dont know is it correct or not ... thanks for your help ...
public class Student
{
private String Name;
private float Mark;
/**
* #return the Name
*/
public String getName() {
return Name;
}
/**
* #param Name the Name to set
*/
public void setName(String Name) {
this.Name = Name;
}
/**
* #return the Mark
*/
public float getMark() {
return Mark;
}
/**
* #param Mark the Mark to set
*/
public void setMark(float Mark) {
this.Mark = Mark;
}
}
Just override the toString() method in Student class, and return the appropriate string you want to get printed when you print an instance.
It may look like: -
#Override
public String toString() {
return "Name: " + studentName;
}
Currently, the default implementation of toString() method of Object class is invoked, and what you are seeing is the format returned from that method, which is of the form - Type#hashCode
Here I've added some stuff how toString() method can be override
public class Student {
private String name;
private int id;
float mark;
public Student() {
}
public Student(String name, int id) {
this.name = name;
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getMark() {
return mark;
}
public void setMark(float mark) {
this.mark = mark;
}
#Override
public String toString() {
return "Student[ID:" + id + ",Name:" + name + ",Mark:"+mark+"]";
}
public void printStudentInfo() {
// print all the details of student
}
public static void main(String[] args) {
Student[] students = new Student[10];
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < students.length; i++) {
System.out.println("Enter Student Name " + (i + 1) + ":");
String name = scanner.nextLine();
Student student = new Student(name, i + 1);
System.out.println("Enter Student MARK Number " + (i + 1) + ":");
float mark = scanner.nextFloat();
student.setMark(mark);
students[i]=student;
}
for(Student student:students) {
// by default toStirng method is called
System.out.println(student);
//or you can call like
//student.printStudentInfo();
}
}
}
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");
}
}
}