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.
Related
Trying to make it so if the user types "end", in the second input which is "Enter the first name of student", the loop automatically assigns each object in the array the attributes of "null" for id and name, and 0 for age and id, as well as breaking the outerloop. However, I get the error java.lang.NullPointerException.
Any help would be appreciated.
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
System.out.println("Enter number of students");
int numberof = myObj.nextInt();
System.out.println("Number of students is " + numberof);
Student Studentz[] = new Student[numberof];
outerloop:
for (int i = 0; i < numberof; ++i) {
Studentz[i] = new Student();
System.out.println("Enter first name of student " + (i + 1));
Scanner myObj1 = new Scanner(System.in);
String firstname = myObj1.nextLine();
System.out.println("Firstname is: " + firstname);
if (firstname.equals("end")) {
for (int g = i; g < numberof; ++g) {
Studentz[g].Setfirst("null");
Studentz[g].Setlast("null");
Studentz[g].Setage(0);
Studentz[g].Setid(0);
}
break outerloop;
} else {
Studentz[i].Setfirst(firstname);
System.out.println("Enter last name of student " + (i + 1));
Scanner myObj2 = new Scanner(System.in);
String lastname = myObj2.nextLine();
System.out.println("Last name is: " + lastname);
Studentz[i].Setlast(lastname);;
System.out.println("Enter age of student " + (i + 1));
Scanner myObj3 = new Scanner(System.in);
int nazca = myObj3.nextInt();
System.out.println("Age is: " + nazca);
Studentz[i].Setage(nazca);
System.out.println("Enter ID of student " + (i + 1));
Scanner myObj4 = new Scanner(System.in);
int nazca1 = myObj4.nextInt();
System.out.println("ID is: " + nazca1);
Studentz[i].Setid(nazca1);
}
for (int c = 0; c < numberof; ++c) {
System.out.println(Studentz[c].Snake());
}
}
}
}
public class Student {
private String first;
private String last;
private int age;
private int id;
public int getid() {
return
this.id;
}
public void Studentss(String f, String l, int a, int i) {
first = f;
last = l;
age = a;
id = i;
}
public void Setfirst(String z) {
this.first = z;
}
public void Setlast(String za) {
this.last = za;
}
public void Setage(int zb) {
this.age = zb;
}
public void Setid(int zc) {
this.id = zc;
}
public String Snake() {
String snek = "Name is " + this.first + " " + this.last + " , Age is " + this.age + " ,ID is " + this.id;
return snek;
}
}
you fail here because you try to print students data before you initialized all elements of Studentz array:
for (int c = 0; c < numberof; ++c) {
System.out.println(Studentz[c].Snake());
}
also your code fails here by the same reason:
for (int g = i; g < numberof; ++g) {
Studentz[g].Setfirst("null"); // NPE - no Student created yet in the array
Some Possibly Helpful Tips:
Follow Java naming rules for your variables and method names, Studentz should be studentz, even for your Arrays. I know...your tired of reading that but as you progress, you'll see how beneficial it really is.
If you can, don't use multiple Scanner objects, there is no need for that in your use-case. Declare one Scanner object and stick with it. You're probably doing this because you are using the nextLine() method after the nextInt() method and you're finding that it skips the first name prompt and provides a Null String (""). This happens because the nextInt() method does not consume the newline character when the Enter key is hit. To solve this problem you would either, place the code line myObj.nextLine(); directly under the int numberof = myObj.nextInt(); code line:
int numberof = myObj.nextInt();
myObj.nextLine(); // Consume ENTER key hit
or don't use the nextInt() method at all. Instead just stick with the nextLine() method and not worry about consumption:
Scanner myObj = new Scanner(System.in);
int numberof = 0;
String val = "";
while (val.equals("")) {
System.out.println("Enter number of students");
val = myObj.nextLine();
if (!val.matches("\\d+")) {
System.err.println("Invalid number supplied!");
val = "";
continue;
}
numberof = Integer.parseInt(val);
}
System.out.println("Number of students is " + numberof);
Student[] studentz = new Student[numberof];
It's always a good idea to validate any input from the User (as shown above), even if they're in a for loop. Give the User an opportunity to make a correct entry, after all, typo's do happen.
Get rid of the outerLoop: label. As a matter of fact, try avoid ever using them if you can....and you can. It would only be on a relatively rare occasion where you might ever need one.
Give your variables meaningful names, at least to some extent. This can benefit you later on down the road when you want to read your old code in the future.
In your Student class you made yourself a this real nice method named Studentss(). Well, I think it should be a constructor instead and save yourself a lot of code entry for calls to Setter methods. After all, that's mostly what the constructor is for. Your Student class constructor can look like this:
public Student(String firstName, String lastName, int age, int id) {
this.first = firstName;
this.last = lastName;
this.age = age;
this.id = id;
}
And be used like this. You will notice that upon each iteration of the outer for loop, all the prompt answers are placed within variables then at the end of all those prompts the constructor is used instantiate a student object, for example:
studentz[i] = new Student(firstname, lastname, age, id);
Doing it this way mean that there is no need to make calls to Setter methods. There is nothing wrong with making setter calls, it's just easier using the constructor. This is demonstrated below:
Scanner myObj = new Scanner(System.in);
int numberof = 0;
String val = "";
while (val.equals("")) {
System.out.println("Enter number of students");
val = myObj.nextLine();
if (!val.matches("\\d+")) {
System.err.println("Invalid number supplied!");
val = "";
continue;
}
numberof = Integer.parseInt(val);
}
System.out.println("Number of students is " + numberof);
Student[] studentz = new Student[numberof];
for (int i = 0; i < numberof; ++i) {
String firstname = "null";
String lastname = "null";
int age = 0;
int id = 0;
boolean exitOuterForLoop = false;
// Student First Name Prompt:
// (with option to End and default remaining to null's and 0's)
while (firstname.equals("null")) {
System.out.println("Enter first name of student " + (i + 1) + " (End to stop):");
firstname = myObj.nextLine();
if (firstname.equalsIgnoreCase("end")) {
firstname = "null";
//Make all remaining Student instances null and 0
for (int g = i; g < numberof; ++g) {
studentz[g] = new Student(firstname, lastname, age, id); // Use Student class constructor
}
exitOuterForLoop = true;
break; // Exit this 'while' loop
}
// Validate first name (no numbers or crazy characters)
if (!firstname.matches("(?i)[a-z']+")) {
System.err.println("Invalid First Name! (" + firstname + ") Try Again...");
firstname = "null";
}
}
if (exitOuterForLoop) {
break; // Exit this outer 'for' loop.
}
System.out.println("Firstname is: " + firstname);
// Student Last Name Prompt
while (lastname.equals("null")) {
System.out.println("Enter last name of student " + (i + 1));
lastname = myObj.nextLine();
// Validate last name (no numbers or crazy characters)
if (!lastname.matches("(?i)[a-z']+")) {
System.err.println("Invalid Last Name! (" + lastname + ") Try Again...");
lastname = "null";
}
}
System.out.println("Last name is: " + lastname);
// Student Age Prompt
val = "";
while (val.equals("")) {
System.out.println("Enter age of student " + (i + 1));
val = myObj.nextLine();
// Validate age (digits 0 to 9 only)
if (!val.matches("\\d+")) {
System.err.println("Invalid Age Supplied! (" + val + ") Try Again...");
val = "";
}
}
age = Integer.parseInt(val);
System.out.println("Student age is: " + age);
// Student ID Prompt
val = "";
while (val.equals("")) {
System.out.println("Enter ID of student " + (i + 1));
val = myObj.nextLine();
// Validate age (digits 0 to 9 only)
if (!val.matches("\\d+")) {
System.err.println("Invalid ID Supplied! (" + val + ") Try Again...");
val = "";
}
}
id = Integer.parseInt(val);
System.out.println("Student ID is: " + id);
studentz[i] = new Student(firstname, lastname, age, id); // Use Student class constructor
}
// Display the instances of Student contained within the 'studentz[]' array.
for (int c = 0; c < numberof; ++c) {
System.out.println(studentz[c].toString());
}
The snake() method is actually just another toString() method and there is nothing wrong with that however you might want to consider using StringBuilder class to create the returned string rather than doing concatenations, for example:
public String snake() {
return new StringBuilder("Name is ").append(this.first).append(" ").append(this.last)
.append(" , Age is ").append(this.age).append(" , ID is ")
.append(this.id).toString();
}
Not overly important here but it can save you memory if you do a lot concatenating with many large strings.
how to print Junior, Intermediate,Seniour as string as per age,and must generate roll number and these input must b generated from the user. Ex: junior name:Rahul age:22, roll:1000 intermediate name:prem age:40, roll:1001 senior name: Vamsi age:60, rollno:1002
String name;
static int age;
public static void main(String[] args) {
int size = 3;
DB[] studs = new DB[size];
for (int i = 0; i < size; i++) {
studs[i] = readStudent(i);
}
for (int i = 0; i <studs.length; i++) {
if(age <=30) {
System.out.println( studs[i]);
}else if(age <=40) {
System.out.println("Intermidiate" +" "+studs[i]);
}else {
System.out.println("Seniour" +" "+studs[i]);
}
}
}
static DB readStudent(int i) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name:");
String name = sc.nextLine();
System.out.print("Enter your age:");
int age = sc.nextInt();
DB studs = new DB(name, age);
return studs;
}
}
class juniourStudent extends Student {
String rollno = "juniour";
static int juniourcount = 1000;
juniourStudent(String name, int age) {
rollno = "juniour" + juniourcount++;
}
}
class intermidiateStudent extends Student {
String rollno = "intermidiate";
static int intermidiatecount = 1000;
intermidiateStudent(String name, int age) {
rollno = "intermidiate" + intermidiatecount++;
}
}
class seniourStudent extends Student {
String rollno = " seniour";
static int seniourcount = 1000;
seniourStudent(String name, int age) {
rollno = "seniour" + seniourcount++;
}
}
There are quite a few issues with your code.
Your class structure is counter-intuitive to what you are trying to do. Based on the example output, it seems that you want the rollNo to increase every time a student is made. It also seems to be redundant to create separate classes when the only thing that differs between them is the prefix (like junior, senior, intermediate, etc.). Instead of making multiple classes, why not add an instance variable to your student class. (Also import Scanner so we can use it later for user input, and ArrayList to store the student data) For Example:
import java.util.Scanner;
import java.util.ArrayList;
public class Student {
String name;
String studentType;
int age;
int rollno;
static int schoolRollno = 1000;
Next you should make a proper constructor for your student class consisting of a String name and an int age, and assigning them to the instance variables we declared earlier. We will assign the studentType variable based upon their age, and we will obtain the students rollno from the static variable. We must increment the static variable so the next student will have a different roll number. (You can change the age comparisons to whatever number you need, but these numbers are what I pieced together from your code)
public Student(String name, int age) {
this.name = name;
if(age <= 30) {
this.studentType = "Junior";
}
else if(age <= 40) {
this.studentType = "Intermediate";
}
else {
this.studentType = "Senior";
}
this.age = age;
this.rollno = schoolRollno;
schoolRollno++;
}
The last thing we need to do before we work on our main function is to write a toString() method for our student class. Based upon the output, you might want a method like this:
#Override
public String toString() {
return studentType + " name: " + name + " age: " + age + ", roll: " + rollno;
}
Now we can take a look at the public static void main(String args[]) function. We have a few things we need to do here. Since it appears we do not know the number of students we are going to be adding, we should use an ArrayList. We should also instantiate our scanner here as well:
ArrayList<Student> students = new ArrayList<Student>();
Scanner scan = new Scanner(System.in);
Now we should create a while loop that allows the user to continue inputting students and wish to stop. Personally, I'm a fan of the do/while loop, so I'll do it that way. We'll need to declare our variable outside of the loop so that we can use it as a conditional for the loop.
boolean done = false;
do {
//(inner loop code here)
} while(!done);
//end loop code
Now for the inner loop code. We need to obtain a String (name) from the user and an int (age). Once we obtain the inputs, we want to construct a Student object and add it to our ArrayList. Then, after all that, we want to see if the user wants to input another student (by changing the value of our boolean we used when declaring the first do/while loop according to the user's input). We can do all this using scanner like so:
System.out.println("Enter name:");
String name = scan.nextLine();
System.out.println("Enter age:");
int age = scan.nextInt();
//we use scan.nextLine() here because scan.nextInt() does not read to the end of the line
scan.nextLine();
Student s = new Student(name, age);
students.add(s);
boolean validInput = true;
do {
validInput = true;
System.out.println("Continue? (y/n)");
String input = scan.nextLine();
if(input.equalsIgnoreCase("y")) {
done = false;
}
else if(input.equalsIgnoreCase("n")) {
done = true;
}
else {
validInput = false;
}
} while(!validInput);
Finally, we want to print the students once we are done. We can print all the students in our ArrayList easily using a for-each loop. (This goes at the end of our main(String args[]) method)
for(Student s: students) {
System.out.println(s.toString());
}
TL;DR:
Combine your classes into one student class
Fix the constructor
Add a toString() method
Use an ArrayList to store the students b/c we don't know the number. (DB isn't a class in java, and an array is counter-intuitive when you don't know what size you'll need)
Create a loop that the user can break out of when they wish to
Obtain user input for the name and age, and use this to construct a student object and add it to the ArrayList
Print out all the students in the ArrayList after the loop
I am a student and looking for help with an assignment. Here is the task: Create a CollegeCourse class. The class contains fields for the course ID (for example, “CIS 210”), credit hours (for example, 3), and a letter grade (for example, ‘A’).
Include get() and set()methods for each field. Create a Student class containing an ID number and an array of five CollegeCourse objects. Create a get() and set() method for the Student ID number. Also create a get() method that returns one of the Student’s CollegeCourses; the method takes an integer argument and returns the CollegeCourse in that position (0 through 4). Next, create a set() method that sets the value of one of the Student’s CollegeCourses; the method takes two arguments—a CollegeCourse and an integer representing the CollegeCourse’s position (0 through 4).
I am getting runtime errors on the second for loop where I am trying to get the data into the course array. It is asking for both the CourseID and Hours in the same line and regardless of what I respond with it I am getting an error, it almost seems like it is trying to get all the arrays variables at the same time. Here is my code which includes three classes. Any help to send me in the right direction is appreciated as I have spent a ton of time already researching to resolve.
public class CollegeCourse {
private String courseId;
private int creditHours;
private char grade;
public CollegeCourse(String id, int hours, char grade)
{
courseId=id;
creditHours = hours;
this.grade = grade;
}
public void setCourseId(String id)
{
courseId = id;//Assign course id to local variable
}
public String getCourseId()
{
return courseId;//Provide access to course id
}
public void setHours(int hours)
{
creditHours = hours;//Assign course id to local variable
}
public int getHours()
{
return creditHours;//Provide access to course id
}
public void setGrade(char grade)
{
this.grade = grade;//Assign course id to local variable
}
public char getGrade()
{
return grade;//Provide access to course id
}
}
Student Class
public class Student {
final int NUM_COURSES = 5;
private int studentId;
private CollegeCourse courseAdd;//Declares a course object
private CollegeCourse[] courses = new CollegeCourse[NUM_COURSES];
//constructor using user input
public Student(int studentId)
{
this.studentId=studentId;
}
public void setStudentId(int id)
{
studentId = id;//Assign course id to local variable
}
public int getStudentId()
{
return studentId;//Provide access to course id
}
public void setCourse(int index, CollegeCourse course)
{
courses[index] = course;
}
public CollegeCourse getCourse(int index)
{
return courses[index];
//do I need code to return the courseId hours, grade
}
}
InputGrades Class
import java.util.Scanner;
public class InputGrades {
public static void main(String[] args) {
final int NUM_STUDENTS = 2;
final int NUM_COURSES = 3;
Student[] students = new Student[NUM_STUDENTS];
int s;//subscript to display the students
int c;//subscript to display courses
int stId;
int csIndex;
String courseId = "";
int hours = 0;
//String gradeInput;
char grade = 'z';
CollegeCourse course = new CollegeCourse(courseId,hours, grade);//not sure if I am handling this correctly
Scanner input = new Scanner(System.in);
for(s = 0; s<NUM_STUDENTS; ++s)
{
students[s] = new Student(s);
System.out.print("Enter ID for student #" + (s+1) + ":");
stId = input.nextInt();
input.nextLine();
students[s].setStudentId(stId);
for(c=0; c < NUM_COURSES; ++c)
{
csIndex=c;
System.out.print("Enter course ID #" + (c+1) + ":");
courseId = input.nextLine();
course.setCourseId(courseId);
System.out.print("Enter hours:");
hours = input.nextInt();
input.nextLine();
course.setHours(hours);
String enteredGrade = "";
while(enteredGrade.length()!=1) {
System.out.print("Enter grade:");
enteredGrade = input.nextLine();
if(enteredGrade.length()==1) {
grade = enteredGrade.charAt(0);
} else {
System.out.println("Type only one character!");
}
}
course.setGrade(grade);
students[s].setCourse(csIndex, course);
}
}
for(s = 0; s<NUM_STUDENTS; ++s)
{
System.out.print("\nStudent# " +
students[s].getStudentId());
System.out.println();
for(c=0;c<NUM_COURSES;++c)
System.out.print(students[s].getCourse(c) + " ");
System.out.println();
}
}
}
After input.nextInt() you need to add one more input.nextLine(); and than you can read grade.
System.out.print("Enter hours:");
hours = input.nextInt();
input.nextLine();
course.setHours(hours);
Why it is needed? See this question: Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
You should add a very simple length validation when you input the grade:
String enteredGrade = "";
while(enteredGrade.length()!=1) {
System.out.print("Enter grade:");
enteredGrade = input.nextLine();
if(enteredGrade.length()==1) {
grade = enteredGrade.charAt(0);
} else {
System.out.println("Type only one character!");
}
}
so the full main class code:
import java.util.Scanner;
/**
* Created by dkis on 2016.10.22..
*/
public class App {
public static void main(String[] args) {
final int NUM_STUDENTS = 10;
final int NUM_COURSES = 5;
Student[] students = new Student[NUM_STUDENTS];
//String name;
int s;//subscript to display the students
int c;//subscript to display courses
int stId;
int csIndex;
String courseId = "";
int hours = 0;
char grade = 'z';
CollegeCourse course = new CollegeCourse(courseId,hours, grade);//not sure if I am handling this correctly
Scanner input = new Scanner(System.in);
for(s = 0; s<NUM_STUDENTS; ++s)
{
students[s] = new Student(s);
System.out.print("Enter ID for student #" + s+1 + ":");
stId = input.nextInt();
input.nextLine();
students[s].setStudentId(stId);
for(c=0; c < NUM_COURSES; ++c)
{
//CollegeCourse course = students[s].getCourse(c);
csIndex=c;
System.out.print("Enter course ID#" + c+1 + ":");
courseId = input.nextLine();
course.setCourseId(courseId);
System.out.print("Enter hours:");
hours = input.nextInt();
input.nextLine();
course.setHours(hours);
String enteredGrade = "";
while(enteredGrade.length()!=1) {
System.out.print("Enter grade:");
enteredGrade = input.nextLine();
if(enteredGrade.length()==1) {
grade = enteredGrade.charAt(0);
} else {
System.out.println("Type only one character!");
}
}
course.setGrade(grade);
students[s].setCourse(csIndex, course);
}
}
for(s = 0; s<NUM_STUDENTS; ++s)
{
System.out.print("\nStudent# " +
students[s].getStudentId());
for(c=0;c<NUM_COURSES;++c)
System.out.print(students[s].getCourse(c) + " ");
System.out.println();
}
}
}
I am trying to have the user type in the last name and first name of a student in an array so that I can call the student information and use it in a grade book.
The Student class has a method called Student(String last_name, String first_name)
I cannot figure out how to make it print students in a list such as:
last name, first name
last name, first name
Here is my program so far:
public static void main (String[] args)
{
System.out.println("--------------------------------");
System.out.println("Welcome to the Gradebook Program");
System.out.println("--------------------------------");
System.out.println();
students = GetNumberOfStudents();
//Allocate space for student information
Student student[] = new Student[students];
for (int i = 0; i < students; i++)
{
System.out.println("Student #" + (i+1));
System.out.print("\tEnter last name: ");
student[i] = scan.nextLine();
System.out.print("\tEnter first name: ");
student[i] = scan.nextLine();
}
System.out.println(student[i]);
I expect we would need to see the definition of Student, you have given the constructor but not the getters/setters.
I would expect the printing code to look something like
for (Student s : student) {
System.out.println(s.getLastName() + "," + s.getFirstName());
}
You are also not initialising your Student objects correctly.
Inside the loop you have written I would expect to see
new Student(lastname, firstname);
Here is a soltuion with a student class which looks like in your description.
package test; //change to your package name
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Student{
private String m_LastName;
private String m_FirstName;
private int[] TestScores = new int[3];
//Constructor
public Student(String last, String first) {
m_LastName = last;
m_FirstName = first;
}
//returns firstname
public String firstName() {
return m_FirstName;
}
//returns lastname
public String lastName() {
return m_LastName;
}
//set a test score at a given index
public void setTestScore(int index, int score) {
TestScores[index] = score;
}
//returns test score at a given index
public int testScore(int index) {
return TestScores[index];
}
//returns testscores average
public double testAverage() {
int sum = 0;
for(int i = 0; i<TestScores.length; i++) {
sum += TestScores[i];
}
return sum/TestScores.length;
}
//returns students highest test score
public int maxTestScore() {
//sort the array
for(int i = 0; i<TestScores.length; i++) {
for(int j = 0; j<TestScores.length; j++) {
if(TestScores[i]<TestScores[j]) {
int buffer;
buffer = TestScores[i];
TestScores[i] = TestScores[j];
TestScores[j] = buffer;
}
}
}
return TestScores[TestScores.length-1];
}
public boolean isPassing() {
//TODO: when hes passing?
return true;
}
public static void main (String[] args)
{
Scanner scan = new Scanner(new InputStreamReader(System.in));
System.out.println("--------------------------------");
System.out.println("Welcome to the Gradebook Program");
System.out.println("--------------------------------");
System.out.println();
/**
* dont know where you declare the students variable
* and how the getnumberofstudents function looks like
*
* students = GetNumberOfStudents();
*/
int students = 1;
List<Student> StudentList = new ArrayList<>(); //creat a list which can store student objects
for (int i = 0; i < students; i++)
{
System.out.println("Student #" + (i+1));
System.out.print("\tEnter last name: ");
String lastname = scan.nextLine(); //store lastname in a variable
System.out.print("\tEnter first name: ");
String firstname = scan.nextLine(); //store firstname in a variable
Student student = new Student(lastname, firstname); //creat new student object with the last and firstname
StudentList.add(student); //add it to the student list
}
//print out all students first and lastnames. here you can add the other data you want to print.
for (int i = 0; i < students; i++)
{
System.out.println("List of all Students:");
System.out.println("Firstname:"+StudentList.get(i).firstName()+" Lastname:"+StudentList.get(i).lastName());
}
}
}
public class Roster extends ArrayList<Student>
{
public boolean containsStudent(String ln)
{
Scanner user_input = new Scanner (System.in);
System.out.println("Enter last name of student: ");
String lName = user_input.next();
for (Student student : this)
{
if (student.getLastName().equals(lName))
return true;
}
return false;
}
How can I fix the error in the next method:
public Student retrieveByld(int id)
{
Scanner user_input = new Scanner (System.in);
System.out.println("Enter the ID of the student: ");
String idNum = user_input.next();
for (Student student : this)
{
if (student.getID().equals(idNum))
return student.getFullName();
}
return " ";
}
Error: int cannot be dereferenced. I'm guessing I cannot compare to ints using the .equals method but how can I without changing the syntax too much.
Given the id, I have to make the program find the student in the list and return that students full name. If student not found I have to return null. If it helps here's my Student class.
public class Student
{
private String lName, fName;
private int idNum;
public Student(int id, String fn, String ln)
{
lName = ln;
fName = fn;
idNum = id;
}
public String getFullName()
{
return fName + " " + lName;
}
public String getLastName()
{
return lName;
}
public String getFirstName()
{
return fName;
}
public int getID()
{
return idNum;
}
public String toString()
{
return fName + " " + lName + " " + idNum;
}
}
ints do not have the equals() method to see if they are equal, they use the == operator, as it's a primitive type. What you're looking for to change is the line if (student.getID().equals(idNum)), which should be: if (student.getID() == idNum).
Your getID() method returns an int, which is a primitive type, meaning it does not have any methods, including the "equals" that you're trying to call. So, either you need to change your idNum from a String to an int, or you need to change what you get back from student.getID() to a String.
Since you're using a Scanner, that has a nextInt() method, which will return the user input as an int. Then you just check for equals using the standard == operator.
Something like this:
public Student retrieveByld(int id)
{
Scanner user_input = new Scanner (System.in);
System.out.println("Enter the ID of the student: ");
int idNum = user_input.nextInt();
for (Student student : this)
{
if (student.getID() == idNum)
return getFullName();
}
return " ";
}
Use Integer class. It's a wrapper around int, giving you access to such things as equals() method: http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Integer.html