I have to find the highest scoring student and the lowest scoring student from the given user input.but i only get the highest scoring student and can't get the lowest scoring student from it.
public class Student{
public String name;
public String id;
public int score;
public static int n;
public Student(String initName,String initID,int initScore){
initName=name;
initID=id;
initScore=score;
}
public Student (){
}
public static void main(String[] args) {
System.out.println("Enter the number of students:");
Scanner s1=new Scanner(System.in);
Student.n=Integer.parseInt(s1.nextLine().trim());
System.out.println("Enter the student name,id and score.");
Scanner s2=new Scanner(System.in);
Student st1=new Student();
Student min=new Student(" "," ",100);
Student max=new Student(" "," ",0);
for(int i=0;i<Student.n;i++){
st1.name=s2.next();
st1.id=s2.next();
st1.score=s2.nextInt();
if(max.score<st1.score){
max.score=st1.score;
max.name=st1.name;
max.id=st1.id;
}
if(min.score>st1.score){
min.name=st1.name;
min.score=st1.score;
min.id=st1.id;
}
}
System.out.println("the highest scoring student: "+max.name);
System.out.println("the lowest scoring student: "+min.name);
}
}
initScore=score;
Please fix the above line in constructor.
Actually all the assignments are incorrect:
public Student(String initName,String initID,int initScore){
initName=name;
initID=id;
initScore=score;
}
It should be changed to
public Student(String initName, String initId, int initScore) {
name = initName;
id = initId;
score = initScore;
}
Even better
public Student(String name, String id, int score) {
this.name = name;
this.id = id;
this.score = score;
}
Since score is not assigned in the initial construction, it is assigned a default value of 0 and hence impacts the min computation. (as its already at min assuming the scores are positive)
It works for max computation as the scores obtained will be greater than or equal to 0 and will eventually update the score directly(assuming only positive scores are allowed).
I see plenty of problems in your code and it seems you don't really know how to code, which makes me wanna recommend going through some Java tutorial first.
Now to your code:
Student class implementation is just full of flaws, no encapsulation, mistakes in constructor, no idea what n is used for
public class Student {
private String name;
private String id;
private int score;
public Student(String initName, String initID, int initScore){
this.name = initName;
this.id = initID;
this.score = initScore;
}
// declare getters such as these two
public String getName() {
return this.name;
}
public int getScore() {
return this.score;
}
}
your main method has so many mistakes too: you have 2 Scanners, you don't initialize enough students and your iteration is plain wrong
public static void main(String[] args) {
Scanner s1 = new Scanner(System.in);
// get number of students
System.out.println("Enter the number of students:");
int numberOfStudents = s1.nextInt();
// initialize array of students
Student[] array = new Student[numberOfStudents];
for(int i = 0; i < numberOfStudents; i++) {
// get name of the student
System.out.println("Enter the student name:");
String name = s1.nextLine();
// get id of student
System.out.println("Enter the student id:");
String id = s1.nextLine();
// get score of student
System.out.println("Enter the student score:");
int score = s1.nextInt();
array[i] = new Student(name, id, score);
}
// now you have students input
// it's time to find your student
// set the lowest and highest student to first student
Student min = array[0];
Student max = array[0];
for(int i = 1; i < numberOfStudents; i++) {
if(min.getScore() > array[i]) {
min = array[i];
} else if(max.getScore() < array[i]) {
max = array[i];
}
}
System.out.println("the highest scoring student: "+max.getName());
System.out.println("the lowest scoring student: "+min.getName());
}
Carefully check the code again :
public Student(String initName,String initID,int initScore){
initName=name;
initID=id;
initScore=score;
}
Did you get it...? Buggy constructor.
The code should be
public Student(String initName,String initID,int initScore){
name = initName;
id = initID;
score = initScore;
}
Related
I have a simple project in java.
the project is a program for a teacher who wants to enter the grades for his students (three grades for each student) with five private attributes name,grade1, grade2, grade3and average and three methods: readGrades(), GetAverage() and getName(). I but them all but my problem is no matter what I did the output always gave me the average of the latest student I entered not the highest.I should also print his name not the average.
someone told me to use ArrayList but honestly I don't know how??
so if anyone can help me I'll appreciate it.
This is what i have so far
import java.util.Scanner;
class Student {
private String name;
private int grade1, grade2, grade3;
private double average;
void Setgrade1(int g1) {
grade1 = g1;
}
void Setgrade2(int g2) {
grade2 = g2;
}
void Setgrade3(int g3) {
grade3 = g3;
}
int Getgrade1() {
return grade1;
}
int Getgrade2() {
return grade2;
}
int Getgrade3() {
return grade3;
}
int readGrades() { //method that reads grades.
Scanner input = new Scanner(System.in);
int g1, g2, g3;
String name;
char choice;
do {
System.out.println(" --Please enter the student name: ");
name = input.next();
SetName(name);
System.out.println(" --Please enter the first grade: ");
g1 = input.nextInt();
Setgrade1(g1);
System.out.println(" --Please enter the the second grade: ");
g2 = input.nextInt();
Setgrade2(g2);
System.out.println(" --Please enter the the third grade: ");
g3 = input.nextInt();
Setgrade3(g3);
System.out.println(" Do you want to continue? enter the number ");
System.out.println(" 1- YES 2- NO ");
choice = input.next().charAt(0);
}
while (choice != '2');
return choice;
}
void SetAverage(double avr) {
average = avr;
}
double GetAverage() {
average = (grade1 + grade2 + grade3) / 3;
return average;
}
void SetName(String name1) {
name = name1;
}
String getName() {
return name;
}
}
public class TestStudent1 {
public static void main(String args[]) {
Student student = new Student();
student.readGrades();
student.GetAverage();
double i = 0;
double average = student.GetAverage();
if (i < average) {
i = average;
System.out.println("THE HIGHEST AVG :" + i);
}
}
}
A couple of problems in your code here are as follows:
1) It is giving you the output for the latest student is because you are modifying a single object all the time as your logic for entering more grades and name is inside the student itself which should be out.
2) To get the name and not the average you should call getName while printing.
3) To handle multiple students you can take out the logic of asking do you wish to continue in your main method and make an ArrayList of students in the main method to handle multiple student objects or you can do it with other collections as well like
List<Student> students = new ArrayList<>();
From here loop and add the student objects in the list using students.add(studentObj).
Then to get the highest compare the average of the students objects by using getAverage and find the student with the highest average from the list and print it.
That will do it. Try some of it and if you are stuck let us know.
I think your problem is you need to create multiple instances of student object in order to store the data of multiple students. What you did in your code is you will always replace your data with the last input. Here is an example of what you can do.
Student student1 = new Student();
Student student2 = new Student();
Student student3 = new Student();
You will also need a data structure to store all the instances of student object, you can either use Array or ArrayList. You will then add every instance of the student object into your data structure. After that, you can compare the average among all the students in your array.
First of all, remove user interaction method readGrades() from data holder Student class. It should be outside. I think that you should not hold average as separate field. This is not big dial to calculate it every time whey you invoke getAverage() method:
public final class Student {
private final String name;
private int grade1;
private int grade2;
private int grade3;
public Student(String name) {
this.name = name;
}
public void setGrade1(int grade1) {
this.grade1 = grade1;
}
public void setGrade2(int grade2) {
this.grade2 = grade2;
}
public void setGrade3(int grade3) {
this.grade3 = grade3;
}
public double getAverage() {
return (grade1 + grade2 + grade3) / 3.0;
}
public String getName() {
return name;
}
public int getGrade1() {
return grade1;
}
public int getGrade2() {
return grade2;
}
public int getGrade3() {
return grade3;
}
}
Second, do create separate method, that interacts with user (or probably other sources) to retrieved required number of students.
private static List<Student> getStudents() {
try (Scanner scan = new Scanner(System.in)) {
List<Student> students = new ArrayList<>();
char choice;
Student student;
do {
System.out.print(" --Please enter the student name: ");
students.add(student = new Student(scan.next()));
System.out.print(" --Please enter the first grade: ");
student.setGrade1(scan.nextInt());
System.out.print(" --Please enter the the second grade: ");
student.setGrade2(scan.nextInt());
System.out.print(" --Please enter the the third grade: ");
student.setGrade3(scan.nextInt());
System.out.println(" Do you want to continue? enter the number ");
System.out.println(" 1- YES 2- NO ");
choice = scan.next().charAt(0);
} while (choice != '2');
return students;
}
}
And finally very simple client's code:
List<Student> students = getStudents();
students.sort((s1, s2) -> Double.compare(s2.getAverage(), s1.getAverage()));
System.out.println("THE HIGHEST AVG :" + students.iterator().next().getName());
I'm providing an alternate approach that doesn't use List/ArrayList. Since this is homework, I won't provide code.
Since the requirement is to find the student with the highest average, and you're collecting each student and three grades at a time, you only need to keep track of two instances of Student at any one time. The one with the highest grade bestStudent, and the one being entered currentStudent.
After each student is entered, check to see whether currentStudent's average is higher than bestStudent's. If it is she's your new teacher's pet. Otherwise, discard. Keep in mind, you'll need to handle the first student a little bit differently.
You have only one instance object for that class, so, when you read data for more students, the next student will replace the data from the previous student.
In this case, to save all students and get information about all of them, is better use ArrayList, and push all new data to that list.
e.g:
List<Student> students = new ArrayList<>();
And in the end, you can get the average that you need.
Edit:
Code using ArrayList:
Student class
public class Student {
private String name;
private int grade1, grade2, grade3;
private double average;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getGrade1() {
return grade1;
}
public void setGrade1(int grade1) {
this.grade1 = grade1;
}
public int getGrade2() {
return grade2;
}
public void setGrade2(int grade2) {
this.grade2 = grade2;
}
public int getGrade3() {
return grade3;
}
public void setGrade3(int grade3) {
this.grade3 = grade3;
}
public double getAverage() {
return average;
}
public void setAverage(double average) {
this.average = average;
}
public double calculateAverage() {
return (grade1 + grade2 + grade3) / 3;
}
}
Main Class
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
public class MainStudent {
public static void main(String[] args) {
//Create a list of student
List<Student> studentList = new ArrayList<Student>();
Scanner input = new Scanner(System.in);
int g1, g2, g3;
String name;
int choice;
do {
//Instantite a new object student
Student student = new Student();
System.out.println(" --Please enter the student name: ");
name = input.next();
student.setName(name);
System.out.println(" --Please enter the first grade: ");
g1 = input.nextInt();
student.setGrade1(g1);
System.out.println(" --Please enter the the second grade: ");
g2 = input.nextInt();
student.setGrade2(g2);
System.out.println(" --Please enter the the third grade: ");
g3 = input.nextInt();
student.setGrade3(g3);
System.out.println(" Do you want to continue? enter the number ");
System.out.println(" 1- YES 2- NO ");
choice = input.nextInt();
student.setAverage(student.calculateAverage());
//Push a new object to student list
studentList.add(student);
}
while (choice != 2);
//Get student object with the higher average
Student higherStudent = Collections.max(studentList, Comparator.comparing(c -> c.getAverage()));
System.out.println("THE HIGHEST AVG :" + higherStudent.getAverage() + "\n BELONG'S TO: " + higherStudent.getName());
}
}
I have transfer the while code to main method, and create a new method to calculate the average, because the getAverage is how we will retrieve the value calculate.
Edit: Get higher average with simple loop
Replacing:
Student higherStudent = Collections.max(studentList, Comparator.comparing(c -> c.getAverage()));
By:
Student higherStudent = new Student();
for(int i = 0; i < studentList.size(); i++) {
if(i == 0) {
higherStudent = studentList.get(i);
} else if(higherStudent.getAverage() < studentList.get(i).getAverage()) {
higherStudent = studentList.get(i);
}
}
I need to get the average test score from the numbers the user submitted and keep getting infinity. I need to know the average test score.
This is the student class:
public class Student {
private String name;
private int numOfQuizzes;
private double totalScore;
private ArrayList<Integer> scores;
public Student(String name){
this.name = name;
scores = new ArrayList<Integer>();
}
public String getName() {
return name;
} public void addQuiz(int score){
scores.add(score);
}
public double getTotalScore() {
for(int score : scores){
totalScore += score;
}
return totalScore;
}
public double getAverageScore(){
return totalScore/(double)numOfQuizzes;
}
}
This is what i have for the main:
ArrayList<String> scores = new ArrayList<String>();
Scanner inp = new Scanner(System.in);
// Request the name
System.out.print("What is your name? ");
String name = inp.nextLine();
// Create the student object
Student student = new Student(name);
// Ask for the grades
System.out.print("Please enter your scores (q to quit): ");
String grade = inp.nextLine();
while (!grade.equals("q")) {
// Convert the grade to an integer and pass it
**student.addQuiz(Integer.parseInt(grade));**
//this is where the error is
// Request a new grade
grade = inp.nextLine();
}
// Report the results
System.out.println("Students Name: " + student.getName());
System.out.println("Total Quiz Scores: " + student.getTotalScore());
double average = student.getTotalScore()/scores.size();
System.out.println("Average Quiz Score: " + student.getAverageScore());
This is the Output:
What is your name? b
Please enter your scores (q to quit): 95
95
95
q
Students Name: b
Total Quiz Scores: 285.0
Infinity
Average Quiz Score: Infinity
As you can see I get infinity even when dividing the scores by the size.
You need to make few changes in your code as shown below:
Student Class:
public class Student {
private String name;
private double totalScore;
private ArrayList<Integer> scores;
public Student(String name){
this.name = name;
scores = new ArrayList<Integer>();
}
public String getName() {
return name;
} public void addQuiz(int score){
scores.add(score);
}
public double getTotalScore() {
totalScore = 0;
for(int score : scores){
totalScore += score;
}
return totalScore;
}
public double getAverageScore(){
return getTotalScore()/scores.size();
}
}
Main Class:
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
// Request the name
System.out.print("What is your name?: ");
String name = input.nextLine();
// Create the student object
Student student = new Student(name);
// Ask for the grades
System.out.print("Please enter your scores (q to quit): ");
String grade = input.nextLine();
while (!grade.equals("q")) {
// Convert the grade to an integer and pass it
student.addQuiz(Integer.parseInt(grade));
// Request a new grade
grade = input.nextLine();
}
// Report the results
System.out.println("Students Name: " + student.getName());
System.out.println("Total Quiz Scores: " + student.getTotalScore());
System.out.println("Average Quiz Score: " + student.getAverageScore());
}
}
Try to use this code, It will work correctly and display average score instead of Infinity.
Changes Done:
Removed private int numOfQuizzes; from Student class.
Added totalScore = 0; in getTotalScore() method in Student class.
Added return getTotalScore()/scores.size(); in getAverageScore() method in Student class. Here getTotalScore() with return total score and scores.size() will return total number of scores. (3 in case of your example)
Removed ArrayList<String> scores = new ArrayList<String>(); from Main class. As It is not needed in Main class.
Removed double average = student.getTotalScore()/scores.size(); because student.getAverageScore() in next line will calculate and return average value.
I think you've confused yourself holding onto two lists.
Remove the scores list in the main method. Also remove totalScore from the Student class; that is what is called a "calculated field"
Update the method
public double getTotalScore() {
double totalScore = 0;
for(int score : scores){
totalScore += score;
}
return totalScore;
}
Then you'll actually want a loop like this to more accurately handle ordering of input validation
String grade;
do {
grade = inp.nextLine();
if (grade.equals("q")) break;
// Convert the grade to an integer and pass it
student.addQuiz(Integer.parseInt(grade));
} while (true);
Then, remove numOfQuizzes from the Student class.
In the average method, that's where you use
return getTotalScore()/scores.size();
You're currently getting Infinity twice because
The main method scores are never added to
You're never incrementing this.numOfQuizzes in the Student class
So in this program I am asking the size of a class of students, taking in each student and the grade associated with them. myStudents[i] then holds each students name and their grade. The problem I am having now is with both of my selectionSort. I was supposed to arrange each students by grades (from highest to lowest. Which I think I did correctly in public static void selectionSort(student[] myStudents), but I am not sure how I a supposed to print that out using a for loop when I call selectionSort. Any advice to point me in the right direction would be greatly appreciated. Thank you!
import java.util.Scanner;
public class Final4{
public static void main(String[] args) {
Scanner myInput=new Scanner(System.in);
System.out.print("Enter the size of the class: ");
int num = myInput.nextInt();
int array[] = new int[num];
double score;
student[] myStudents = new student[num];
for (int i = 0 ; i < array.length; i++ ) {
System.out.print("Please enter a student name: ");
myInput.useDelimiter(System.getProperty("line.separator"));
String s;
s = myInput.next();
System.out.print("Please enter " + s +"'s score: ");
score = myInput.nextDouble();
myStudents[i] = new student(s, score);
}
}
selectionSort()
public static void selectionSort(student[] myStudents) {
for (int i = myStudents.length-1; i>0; i--){
int maxIndex = 0;
student max = myStudents[0];
for (int j=1; j<=i; j++)
if (myStudents[j].getScore() > (max.getScore())) {
maxIndex = i;
}
student temp = myStudents[i];
myStudents[i] = myStudents[maxIndex];
myStudents[maxIndex] = temp;
}
}
}
class student {
String name;
double score;
student(String name, double score) {
this.name = name;
this.score = score;
}
public double getScore() {
return score;
}
public String getName() {
return name;
}
}
I tend to get a little confused once I start incorporating gets and objects. Again, any advice is greatly appreciated.
so your problem was how to print your array of Student which is sorted by Selection Sort, right?
On your main method, after looping condition (on creating Student array) add this code.
selectionSort(myStudents);
for(Student s: myStudents) {
System.out.println(s.getName() + " " + s.getScore());
}
That code will print your array of students.
I am working on my final and I got to the part I an mildly confused about.
I can't figure out if it's possible to call the Admin or Student inputs with it being outside of the if statement. I need to call the results in the 3rd and 4th option in the menu and I can't do it without it throwing errors.
public class MainEntry {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
int printMenu = 0;
while(printMenu != 5){
printMenu();
printMenu = console.nextInt();
if (printMenu == 1){
String firstName;
String lastName;
int year;
double[] grades;
double studentId;
String major;
int size;
System.out.println("How many students do you have? ");
size = console.nextInt();
Student newStudent = new Student();
int[] stud = new int[size];
for(int i = 0; i < stud.length; i++)
{
System.out.println("What is the students first name? ");
firstName = console.next();
newStudent.setFirstName(firstName);
System.out.println("What is the students last name? ");
lastName = console.next();
newStudent.setLastName(lastName);
System.out.println("What year are they in? ");
year = console.nextInt();
newStudent.setYear(year);
System.out.println("Enter in their grades: ");
grades = console.nextDouble();newStudent.setGrades(grades);
System.out.println("What is their Student ID number? ");
studentId = console.nextDouble();
newStudent.setStudentID(studentId);
System.out.println("What is the student's major? ");
major = console.next();
newStudent.setMajor(major);
}
}
else if (printMenu == 2){
Admin newAdmin = new Admin();
System.out.println("How many admins do you have? ");
int size = console.nextInt();
int[] admins = new int[size];
for(int i = 0; i < admins.length; i++)
{
System.out.println("What is the admin's first name? ");
String firstName = console.next();
newAdmin.setFirstName(firstName);
System.out.println("What is the admin's last name? ");
String lastName = console.next();
newAdmin.setLastName(lastName);
System.out.println("What is their Admin's ID number? ");
double adminId = console.nextDouble();
newAdmin.setAdminId(adminId);
System.out.println("What is the Admin's department? ");
String department = console.next();
newAdmin.setDepartment(department);
System.out.println("What is their salary? ");
int salary = console.nextInt();
newAdmin.setsalary(salary);
}
}
else if (printMenu == 3){
System.out.println("First name: " + newStudent.getFirstName());
System.out.println("Last name: " + newStudent.getLastName());
System.out.println("ID Number: " + newStudent.getStudentID());System.out.println("GPA: " + newStudent.getgrade());System.out.println("Major: "+newStudent.getMajor());
}
else if (printMenu == 4){
System.out.println("First name: " + newAdmin.getFirstName());
System.out.println("Last name: " + newAdmin.getLastName()); System.out.println("ID Number: " + newAdmin.getAdminId()); System.out.println("GPA: " + newAdmin.getgrade());
System.out.println("Major: " + newAdmin.getsalary());
}
else if(printMenu == 5){
System.out.println("Thanks for using my program!");
}
}
}
// This method will bring up the beginning menu for the user
public static void printMenu(){
//Asking the user which option they are selecting
System.out.println("How would you like to input your data?");
System.out.println("1. Enter in students. ");
System.out.println("2. Enter in admins. ");
System.out.println("3. Print the student information. ");
System.out.println("4. Print admin information. ");
System.out.println("5. Exit the program. ");
}
}
For the student grade I need to average there 5 grades together using an array.
public class Student {
// stores the first name
private String firstName;
// stores the last name
private String lastName;
// stores the
private int year;
// stores the grades
private double[] grades;
// stores the ID number
private double studentID;
private String major;
public static int studentInfo;
//here is where it sets the defaults
public Student(){
firstName = "Jane";
lastName = "Doe";
year = 1;
grades = new double[]{0,0,0,0,0};
studentID = 0;
major = "undeclared";
studentInfo++;
}
public static int studentInfo(){
return (studentInfo);
}
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 getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public double[] getGrades() {
return grades;
}
public void setGrades(double[] grades) {
this.grades = grades;
}
public double getStudentID() {
return studentID;
}
public void setStudentID(double studentID) {
this.studentID = studentID;
}
public String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
public static int getStudentInfo() {
return studentInfo;
}
public static void setStudentInfo(int studentInfo) {
Student.studentInfo = studentInfo;
}
public Student(String firstName, String lastName, int year, double[] grades, double studentID){
this.firstName = firstName;
this.lastName = lastName;
this.year = year;
this.grades = grades;
this.studentID = studentID;
studentInfo++;
}
}
I understand how to build it in the class side but I don't understand how to use it in MainEntry. It keeps asking me to change type and I can't figure out what else to do to fix it. I have issues with arrays so that's something that I'm not quite the best at...
Any help is appreciated.
1) For this, you need to declare newStudent outside of the if statement.
while(printMenu != 5){
Student newStudent = null; // ← newStudent is declared here
printMenu();
printMenu = console.nextInt();
This means that you don't declare it later, only assign to it the result of the new operator:
int size;
System.out.println("How many students do you have? ");
size = console.nextInt();
newStudent = new Student(); // ← this is only an assignment, not a declaration
It also means that you have to be careful when the user wants to display the information concerning the student, because newStudent can be null (i.e. no information have been entered yet).
2) The average is not a double array, just a double. This is why the compiler complains about incompatible types. The average will not be computed automatically, you have to do it yourself. Basically, you need two steps. First, iterate through the array and calculate the sum of the elements:
double sum = 0;
for (double g : grades) { // do this for all elements of the array
sum += g; // add the element to the sum
}
Then, the average is the sum divided by the number of elements.
double average = sum / grades.length;
I'm getting the NullPointerException when I use this method. Someone told me it is because student.getId() returns a null. I have tried to fix this, but I can't figure it out. Below is just a snippet of the code, just the method and the Student class.
edit: I added the part where the array was created.
Student[] students ;
public Student[] enterStudents(){
Scanner input = new Scanner(System.in);
System.out.println("Enter number of students");
int numOfStudents = input.nextInt();
Student[] students = new Student[numOfStudents];
int i;
for(i = 0; i <= numOfStudents - 1; i++){
System.out.println("Enter student's ID: ");
int id = input.nextInt();
System.out.println("Enter student's first name: ");
String first = input.next();
System.out.println("Enter student's last name: ");
String last = input.next();
System.out.println("Enter student's class: ");
String stuClass = input.next();
Student x = new Student(id,first,last,stuClass);
students[i] = x;
}
return students;
}
public void retrieveStuId(){
Scanner input = new Scanner(System.in);
System.out.println("Enter student id");
int searchID = input.nextInt();
int i;
for(i = 0; i < students.length; i++){
Student student = students[i];
int search = student.getId();
if (search == searchID) {
System.out.println(student.toString());
}
}
}
class Student{
private int studentID;
private String firstName;
private String lastName;
private String stuClass;
public Student(){
}
public Student(int id, String first, String last, String c ){
studentID = id;
firstName = first;
lastName = last;
stuClass = c;
}
public void setID (int id){
studentID = id;
}
public void setStuClass (String c){
stuClass = c;
}
public void setFirst(String first){
firstName = first;
}
public void setLast(String last){
lastName = last;
}
public String getFirst(){
return firstName;
}
public String getLast(){
return lastName;
}
public int getId(){
return studentID;
}
public String getStuClass(){
return stuClass;
}
public String toString(){
return "Student ID: " + studentID + " --- " + "Student Name: " + firstName + " " + lastName + " --- " + "Class:" + stuClass;
}
}
Thank for any help in advance.
Your students array has null values, which you try to dereference. The bug isn't in the code you posted, rather where the students array is created and filled.
Just check for null values, and print something like "student not found."
for(i = 0; i < students.length; i++){
Student student = students[i];
if ( student != null ) {
int search = student.getId();
if (search == searchID)
System.out.println(student.toString());
}
}
EDIT:
I checked your code, it works, I tested it by adding
public class StudentTest {
public static void main(String[] args) {
StudentTest s = new StudentTest();
}
public StudentTest() {
students = enterStudents();
retrieveStuId();
}
// your code here ...
Student[] students ;
// .... end
}
Check the place where you assign the array returned by enterStudents.
There are two problem with that code. First is related to shadowing as mentioned before.
Second, as long as Im concerned about this code there is problem with not assigned return type to variable. Basically I think you forgotten to assigned return from your method enterStudents to your variable. Hopefully it is clear for you :)
There is an undefined (null) Student in your students array.Check if it's not null then use getID method.
How did you create the student array? Is it initialized with a Student for every position?
To find out print the value of student after this line:
Student student = students[i];
with
System.out.println(student);
for example. Also check whether all the students in the array have been initialized with a
correct ID so getIt() returns a non-null value. (try printing the value after assigning to search).
You have two (that is TWO) declarations for something called students. One of them (the local variable) is being initialized, and the other (the instance variable) is not being initialized. The NullPointerException is being thrown when you try to use the one that is not initialized.
You shouldn't have two declarations.
Since this is homework, I'll leave it to you to figure out which declaration to delete ... and what to do about the other one.