What I have is a two snippets of code. The question I have in particular is about my dropCourse method within the student driver. Everything in my code seems to work fine except when I drop a course it does not drop the courses credits. For example, if I drop a course named "Computer101" which had four credits, it will remove "Computer101" From the schedule, but will not remove the "4" credits when I choose option 5 to print the total credits. So if we have a full schedule of:
Computer101 in position 0 worth 4 credits
Physics105 in position 1 worth 4 credits
Art101 in position 2 worth 4 credits
Chem101 in position 3 worth 4 credits
And I decide to drop Computer101 from the schedule, all other classes will move up in their position in the array as they are supposed to, when printing the schedule that class will no longer show up and when it is searched for it will not be found, but the amount of credits it was worth will still be there. I feel like the solution is right in front of me, but I am so burned out I am not seeing it. I would really appreciate any help and I hope I was clear with what I am asking.
Here is where my dropCourse method will be found:
public class Student
{
//Instance Data
String studentName;
String studentID;
String streetAddress;
String city;
String state;
String zipCode;
String major;
final int MAX_CREDITS = 18;
int courseNumber = 0; //start out with no courses
int totalCredits;
final int SIZE = 6;
String [ ] schedule = new String [SIZE];
//Create Constructor:
//Initializes the student data at instantiation time.
//-------------------------------------------------------
// Sets up the student's information.
//-------------------------------------------------------
public Student (String name, String id, String address, String cityName, String stateName, String zip, String area )
{
studentName = name;
studentID = id;
streetAddress = address;
city = cityName;
state = stateName;
zipCode = zip;
major = area;
}//end Student Constructor
//Method to Return student information as string:
//-------------------------------------------------------
// Returns the student information as a formatted string.
//-------------------------------------------------------
public String toString()
{
String studentInfo;
studentInfo = "Name:\t\t\t" + studentName + "\n" + "ID:\t\t\t" + studentID + "\n" + "Address:\t\t" + streetAddress
+ "\n" + "City:\t\t\t" + city + "\n" + "State:\t\t\t" + state + "\n" + "Zip Code:\t\t" + zipCode
+ "\n" + "Major:\t\t\t" + major + "\n";
return studentInfo;
}// end toString
//Method to determine if maximum allowed credits have been exceeded
//-------------------------------------------------------
// Returns true if total credits does not exceed 18.
//-------------------------------------------------------
private boolean checkCredits(int numCredits)
{
if (numCredits + totalCredits <= MAX_CREDITS) //make sure max credits not exceeded
{
return true; //return a true if still less than 18 credits
}
else
{
return false; //return a false if 18 credit limit is exceeded
}//end numCredits
}//checkCredits
//Method to add a course to the student’s schedule
//-------------------------------------------------------
// Adds a course to the array if total credits does not exceed 18.
//-------------------------------------------------------
public void addCourse(String course, int numCredits)
{
if (courseNumber < SIZE ) //make sure array is not full.
{
if (checkCredits(numCredits) == true) //if we’re under 18 credits
{
//add course
schedule [courseNumber] = course + ":\t\t" + numCredits + "\tCredits\n";
//increment number of credits
totalCredits = totalCredits + numCredits;
//increment number of courses
courseNumber = courseNumber + 1;
System.out.println("The course has been added!");
}
else //oops – can’t do more than 18 credits
{
System.out.println("You have exceeded the maximum allowed credits.");
}//end checkCredits
}
else //oops – can’t do more than 6 courses
{
System.out.println("You have exceeded 6 courses.");
}//end courseNumber
}//addCourse
public void displaySchedule( )
{
for (int index = 0; index < courseNumber; index++)
{
System.out.println("Course #" + (index + 1) + " " + schedule[index] + "\n");
}//end for
}//end display schedule
public int searchCourse(String courseName)
{
String course;
boolean flag = false;
int index = 0;
while(index < courseNumber && flag == false)
{
String extract = schedule[index].substring(0,6);
if (extract.contains(courseName) == true)
{
flag = true;
}
else
{
index++;
}
}
if (flag == false)
{
return -1;
}
else
{
return index++;
}
}
public void dropCourse(String courseName)
{
int found;
found = searchCourse(courseName);
int index = 0;
if (found == -1)
{
System.out.println("Course not in schedule");
}
else
{
if (found == 5)
{
courseNumber = courseNumber -1;
}
else
{
for (index = found; index < courseNumber; index ++)
{
schedule[index] = schedule[index + 1];
}
courseNumber = courseNumber -1;
System.out.println("The course has been dropped!");
}
}
}
public int totalCredits()
{
System.out.println("The total credits are " + totalCredits);
return totalCredits;
}
}//end class Student
This is where my menu that works with the above code is:
//This is a Driver program to test the external Class named Student
import java.util.Scanner;
public class TheMenu //BEGIN Class Definition
{
//**************** Main Method*************************
static Scanner scan = new Scanner(System.in);
public static void main (String[] args)
{
//Data Definitions:
//Instance Data
String name;
String id;
String street;
String city;
String state;
String zip;
String major;
String courseName;
int courseCredits;
int menu = 0;
//Initialize first Student
name = "Florence Welch";//look her up
id = "7777";
street = "777 Heaven Street";
city = "Witchville";
state = "NY";
zip = "12345";
major = "Arts";
//instantiate the Student object
Student student1 = new Student(name, id, street, city, state, zip, major);
while (menu < 6)//begin while for menu options
{
System.out.println("1. Add a course ");
System.out.println("2. Search for a course");
System.out.println("3. Drop a course");
System.out.println("4. Print out a student's schedule");
System.out.println("5. Print out total credits");
System.out.println("6. Exit");
System.out.println("Enter an option: ");
menu = scan.nextInt();
if (menu == 1)//option to add course
{
System.out.println("Please enter the name of the course: ");
courseName = scan.next();
System.out.println("How many credits is the course? ");
courseCredits = scan.nextInt();
student1.addCourse(courseName, courseCredits);//uses method to store course information in array
}
else if (menu == 2)//option to search for course
{
int x;
System.out.println("Please enter the name of the course: ");
courseName = scan.next();
student1.searchCourse(courseName);
x = student1.searchCourse(courseName);
if (x == -1)//course is not found if value returns -1
{
System.out.println("Course not found");
}
else
{
System.out.println("Course found in position " + student1.searchCourse(courseName));//shows user the position of course
}
}
else if (menu == 3)//will drop course from users schedule
{
System.out.println("Please enter the course you wish to drop: ");
courseName = scan.next();
student1.dropCourse(courseName);
}
else if (menu == 4)//displays the users schedule
{
System.out.println(name + "'s Schedule:\n\n");
student1.displaySchedule();
}
else if (menu == 5)//will display users credits for semester
{
student1.totalCredits();
}
else
{
System.out.println("Enjoy your semester!");//option 6 will exit program
}
}
}
}
Related
I'm doing an assignment that asks a user to input a student name, and then quiz scores until the user chooses to stop. It then calculates the total score and the average of all those scores and outputs them to the screen.
We are moving on to the subject of inheritance and now we are requested to make a class called MonitoredStudent which extends Student. The point of the MonitoredStudent class is to check if the average is above a user inputted average and display whether the student is off academic probation.
I have got most of the program written and when I input just one score (such as 71, when the average I set is 70) it is still displaying that I am on academic probation, even though the one quiz score is above the average I set of 70.
The main issue is that no matter what integer is set for the minimum passing average, I always get a return of false.
I added the "return false" statement in the isOffProbation method as when I add an if-else statement to check if the averageScore (from the Student class) is less than or equal to minPassingAvg eclipse tells me that the method needs a return type of boolean.
public class MonitoredStudent extends Student {
int minPassingAvg;
public MonitoredStudent(){
super();
minPassingAvg = 0;
}
public MonitoredStudent(String name, int minPassingAvg) {
super(name);
this.minPassingAvg = minPassingAvg;
}
public int getMinPassingAvg() {
return minPassingAvg;
}
public void setMinPassingAvg(int minPassingAvg) {
this.minPassingAvg = minPassingAvg;
}
boolean isOffProbation() {
if(getAverageScore() >= minPassingAvg)
return true;
return false;
}
}
This is the Student super class:
public class Student{
private String name;
private double totalScore;
private int quizCount;
public Student(){
name = "";
totalScore = 0;
quizCount = 0;
}
public Student(String n){
name = n;
totalScore = 0;
quizCount = 0;
}
public void setName(String aName){
name = aName;
}
public String getName(){
return name;
}
public void addQuiz(int score){
if(score >= 0 && score <= 100){
totalScore = totalScore + score;
quizCount = quizCount + 1;
}else{
System.out.println("Score must be between 0 and 100, inclusive");
}
}
public double getTotalScore(){
return totalScore;
}
public double getAverageScore(){
return totalScore / quizCount;
}
}
This is the main method:
import java.util.Scanner;
public class MonitoredStudentTester{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
MonitoredStudent monStu = new MonitoredStudent();
String repeat = "n";
int currentScore = 0;
int minPassAv;
System.out.println("Enter the student's name:");
String stuName = scan.next();
Student sName = new Student(stuName);
System.out.println("What is the minimum passing average score: ");
minPassAv = scan.nextInt();
Student stu = new Student();
do {
System.out.println("Enter a quiz score: ");
currentScore = scan.nextInt();
stu.addQuiz(currentScore);
monStu.setMinPassingAvg(currentScore);
System.out.println("Would you like to enter any more scores?: (Y for yes, N for no)");
scan.nextLine();
repeat = scan.nextLine();
}while(repeat.equalsIgnoreCase("y"));
String studName = stu.getName();
double totalScore = stu.getTotalScore();
double avgScore = stu.getAverageScore();
boolean offProb = monStu.isOffProbation();
System.out.println(studName + "'s Total Score is: " + totalScore);
System.out.println(studName + "'s Average Score is: " + avgScore);
System.out.println("Is " + studName + "off academic probation?: " + offProb);
}
}
You main class should be something like this.
public class MonitoredStudentTester {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
MonitoredStudent monStu = new MonitoredStudent();
String repeat = "n";
int currentScore = 0;
int minPassAv;
System.out.println("Enter the student's name:");
monStu.setName(scan.next());
System.out.println("What is the minimum passing average score: ");
minPassAv = scan.nextInt();
do {
System.out.println("Enter a quiz score: ");
currentScore = scan.nextInt();
monStu.addQuiz(currentScore);
monStu.setMinPassingAvg(minPassAv);
System.out.println("Would you like to enter any more scores?: (Y for yes, N for no)");
scan.nextLine();
repeat = scan.nextLine();
} while (repeat.equalsIgnoreCase("y"));
String studName = monStu.getName();
double totalScore = monStu.getTotalScore();
double avgScore = monStu.getAverageScore();
boolean offProb = monStu.isOffProbation();
System.out.println(studName + "'s Total Score is: " + totalScore);
System.out.println(studName + "'s Average Score is: " + avgScore);
System.out.println("Is " + studName + "off academic probation?: " + offProb);
}
}
When using inheritance you just need to create an object of child class.
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.
I am having an issue with searching an array for a course;
Here are the parameters:
This method will allow a student to search for a course name from their existing schedule.
Use a WHILE loop that will stop when one of two conditions is true: either the course is found OR you have reached the last course in the schedule and did not have a match.
If the course is found then print out the course name and number of credits.
If the course is not found then print out a message stating the course is not listed on the student's schedule.
Only search through existing courses. If the array is not full and you search the entire array your program will have a run-time error.
Here is my code so far, thank you in advance:
public class Student {
//Instance Data
String studentName;
String studentID;
String streetAddress;
String city;
String state;
String zipCode;
String major;
int totalCredits;
final int MAX_CREDITS = 18;
final int SIZE = 6;
String[] schedule = new String[SIZE];
int courseNumber = 0;
//Create Constructor:
//Initializes the student data at instantiation time.
//-------------------------------------------------------
// Sets up the student's information.
//-------------------------------------------------------
public Student(String name, String id, String address, String cityName, String stateName, String zip, String area) {
studentName = name;
studentID = id;
streetAddress = address;
city = cityName;
state = stateName;
zipCode = zip;
major = area;
} //end Student Constructor
//Method to Return student information as string:
//-------------------------------------------------------
// Returns the student information as a formatted string.
//-------------------------------------------------------
public String toString() {
String studentInfo;
studentInfo = "Name:\t\t\t" + studentName + "\n" + "ID:\t\t\t" + studentID + "\n" + "Address:\t\t" + streetAddress + "\n" + "City:\t\t\t" + city + "\n" + "State:\t\t\t" + state + "\n" + "Zip Code:\t\t" + zipCode + "\n" + "Major:\t\t\t" + major + "\n";
return studentInfo;
} // end toString
//Method to determine if maximum allowed credits have been exceeded
//-------------------------------------------------------
// Returns true if total credits does not exceed 18.
//-------------------------------------------------------
private boolean checkCredits(int numCredits) {
if (numCredits + totalCredits <= MAX_CREDITS) //make sure max credits not exceeded
{
return true; //return a true if still less than 18 credits
} else {
return false; //return a false if 18 credit limit is exceeded
} //end numCredits
} //checkCredits
//Method to add a course to the student’s schedule
//-------------------------------------------------------
// Adds a course to the array if total credits does not exceed 18.
//-------------------------------------------------------
public void addCourse(String course, int numCredits) {
if (courseNumber < SIZE) //make sure array is not full.
{
if (checkCredits(numCredits) == true) //if we’re under 18 credits
{
//add course
schedule[courseNumber] = course + ":\t\t" + numCredits + "\tCredits\n";
//increment number of credits
totalCredits = totalCredits + numCredits;
//increment number of courses
courseNumber = courseNumber + 1;
} else //oops – can’t do more than 18 credits
{
System.out.println("You have exceeded the maximum allowed credits.");
} //end checkCredits
} else //oops – can’t do more than 10 courses
{
System.out.println("You have exceeded 10 courses.");
} //end courseNumber
} //addCourse
//Method to display the schedule
//-------------------------------------------------------
// Will only print out the courses added to the array.
//-------------------------------------------------------
public void displaySchedule() {
for (int index = 0; index < courseNumber; index++) {
System.out.println("Course #" + (index + 1) + " " + schedule[index] + "\n");
} //end for
} //end display schedule
public void searchCourse(String courseName) {
int index;
String extract;
boolean notFound = true;
index = 0;
while (index < SIZE) {
extract = schedule(index).charAt(0, 6);
if (courseName != extract) {
index++;
} else {
notFound = false;
}
if (notFound = true) {
System.out.println("Course Found");
} else {
System.out.println("Course Not Found");
}
}
}
}
Search method doesn't look so efficient, maybe something like this:
while(index++ < SIZE){
extract = schedule(index).charAt(0,6);
if(!(extract == courseName)){ // i belive this returns 0 if true, which would make our if statement false, just use the not operator
// found the course, do stuff
return;
}
}
// if loop ends, then we didn't find the course, do stuff
I can output the details from the student, but always when i do it displays
Exception in thread "main" java.lang.NullPointerException
at client.Client.main(Client.java:126)
and the program crashes.
The array is null , I don't why and I don't know how to fix that. Please help me to understand, the problem should be around here..
if (choice == 3) {
for (int a = 0; a < list.length; a++) { //To Display all current Student Information.
// list[i] = new student();
list[a].DisplayOutput();
}
Anyways here comes my code.
package client;
import java.util.Scanner;
public class Client {
//my infos
public static void AuthorInformation() {
System.out.print("__________________________________________\n"
+ "Student Name: xxxxxx xxxxxx\n"
+ "Student ID-Number: xxxxxx\n"
+ "Tutorial Timing: Wednesday 9:30 - 12:30 \n"
+ "Tutor Name: Mr xxxxxx\n\n"
+ "__________________________________________\n");
}
This is my client Class
public static void main(String[] args) {
AuthorInformation(); //calls the method for my information
student[] list = new student[20]; //my array
student student = new student();
int choice = 0; //variable for the choise of the menu
Scanner keyboard = new Scanner(System.in); //Scanner class
do { //MY menu in the do-while, so that it runs at least once while user enters 7(quit)
student.DisplayQuestions();
choice = keyboard.nextInt(); //takes the entered value from the user
if (choice == 1) {
System.out.println("Enter the Number of Students you want to store: ");//Enter amount of students to be stored
int studentNumber = keyboard.nextInt();
// student.addStudent();
for (int i = 0; i < studentNumber; i++) { //for loop is till the student number is achieved
list[i] = new student();
System.out.println("\nTitle of the student (eg, Mr, Miss, Ms, Mrs etc): ");
list[i].SetTitle(keyboard.next());
System.out.println("First name (given name)");
list[i].SetFirstName(keyboard.next());
System.out.println("A last name (family name/surname)");
list[i].SetFamilyName(keyboard.next());
System.out.println("Student number (ID):");
list[i].SetStudentID(keyboard.nextInt());
System.out.println("Enter the Day of birth(1-31): ");
list[i].SetDay(keyboard.nextInt());
System.out.println("Enter the Month of birth (1-12): ");
list[i].SetMonth(keyboard.nextInt());
System.out.println("Enter The Year of birth: ");
list[i].SetYear(keyboard.nextInt());
System.out.println("Students First Assignment Mark (0 - 100): ");
list[i].SetFirstMark(keyboard.nextInt());
System.out.println("Students Second Assignment Mark (0 - 100): ");
list[i].SetSecondMark(keyboard.nextInt());
System.out.println("Enter the mark of Student weekly practical work (0-10) ");
list[i].SetWeeklyMarks(keyboard.nextInt());
System.out.println("Please Enter the Marks for the final Exam(0 - 100): ");
list[i].SetFinalMark(keyboard.nextInt());
/* System.out.println("- - - - - - - - - - - - -");
System.out.println("Do you want to add another Student? (Yes/No)");
String a = keyboard.next();
if (a.equalsIgnoreCase("yes")) {
} else if (a.equalsIgnoreCase("no")) {
i = list.length + 1;
}*/
}
}
if (choice == 2) {
int x = 2;
double AverageNum = 0;
for (int p = 0; p < x; p++) { //This is to take the Average OverallMarks of all students
AverageNum += list[p].OverallMarking();
}
System.out.println("Total Average Of Overall Marks is :" + AverageNum / 2);
}
if (choice == 3) {
for (int a = 0; a < list.length; a++) { //To Display all current Student Information.
// list[i] = new student();
list[a].DisplayOutput();
}
}
if (choice == 4) { //To Display the distribution of grades awarded.
System.out.println("\nGrade Distribution: \n" + student.GetCounterHD() + " HDs\n" + student.GetCounterD() + " Ds\n" + student.GetCounterC() + " Cs\n" + student.GetCounterP() + " Ps\n" + student.GetCounterN() + " Ns\n");
}
if (choice == 5) {
System.out.println("Enter Student's ID Number to search for: "); // to take the id number from the user
int FindID = keyboard.nextInt();
boolean Found = false;
// to find with the student ID Number details of the student.
for (int i = 0; i < 10; i++) {
if (FindID == list[i].GetStudentID()) {
list[i].DisplayOutput();
Found = true;
break;
}
}
}
if (choice == 6) { //
System.out.println("Enter Student's Name to search for: ");
String SearchStudentName = keyboard.next(); //take the name of the student
boolean Found = false;
//To find the name of the student it loops till it has it or the limit of studentnumbers are achieved.
for (int i = 0; i < list.length; i++) {
if (SearchStudentName.equalsIgnoreCase(list[i].GetFirstName())) {
list[i].DisplayOutput();
Found = true;
break;
}
}
}
} while (choice != 7);
{ //while statement quit the program
System.out.println("\nYou Quit.");
}
}
}
And here is my student class
package client;
import java.util.Scanner;
public class student {
//The instance vriables for students (Title, first name, family name,
Student ID, date of birth in day month and year, first and second
assignment mark, mark of weekly practical work and final exam
private String Title;
private String FirstName;
private String FamilyName;
private long StudentID;
private int Day;
private int Month;
private int Year;
private float FirstMark;
private float SecondMark;
private float WeeklyMarks;
private float FinalMark;
//those private instance variables are for the calculation of (first and
second assignment mark, mark of weekly practical work and exam mark, final
mark and overall mark)
private float FirstMarkPercentage;
private float SecondMarkPercentage;
private float WeeklyMarksPercentage;
private float ExamPercentage;
private String FinalGrade;
private float OverallMarks = 0;
//those private instance variables are to count the the marks(
private int CounterN = 0;
private int CounterP = 0;
private int CounterC = 0;
private int CounterD = 0;
private int CounterHD = 0;
public student(String Title, String FirstName, String FamilyName, long StudentID, int Day, int Month, int Year, float FirstMark, float SecondMark, float WeeklyMarks, float FinalMark) {
this.Title = Title;
this.FirstName = FirstName;
this.FamilyName = FamilyName;
this.StudentID = StudentID;
this.Day = Day;
this.Month = Month;
this.Year = Year;
this.FirstMark = FirstMark;
this.SecondMark = SecondMark;
this.WeeklyMarks = WeeklyMarks;
this.FinalMark = FinalMark;
this.FinalGrade = FinalGrade;
}
//This Method is to display (Title, first name, family name, Student ID, date of birth in day month and year, first and second assignment mark, mark of weekly practical work and final exam)
public student() {
Title = "";
FirstName = "";
FamilyName = "";
StudentID = 0;
Day = 0;
Month = 0;
Year = 0;
FirstMark = 0;
SecondMark = 0;
WeeklyMarks = 0;
FinalMark = 0;
}
//The methods starting with Get...(), are to return the (Title, first name, family name, Student ID, date of birth in day month and year, first and second assignment mark, mark of weekly practical work and final exam and the marks N, P, C, D & HD)
public String GetTitle() {
return Title;
}
public String GetFirstName() {
return FirstName;
}
public String GetFamilyName() {
return FamilyName;
}
public long GetStudentID() {
return StudentID;
}
public int GetDay() {
return Day;
}
public int GetMonth() {
return Month;
}
public int GetYear() {
return Year;
}
public float GetFirstMark() {
return FirstMark;
}
public float GetSecondMark() {
return SecondMark;
}
public float GetWeeklyMarks() {
return WeeklyMarks;
}
public float GetFinalMark() {
return FinalMark;
}
public String GetFinalGrade() {
return FinalGrade;
}
public int GetCounterHD() {
return CounterHD;
}
public int GetCounterD() {
return CounterD;
}
public int GetCounterC() {
return CounterC;
}
public int GetCounterP() {
return CounterP;
}
public int GetCounterN() {
return CounterN;
}
public float GetOverallMarks() {
return OverallMarks;
}
//The methods starting with Set...(), are to set the (Title, first name, family name, Student ID, date of birth in day month and year, first and second assignment mark, mark of weekly practical work and final exam and the marks N, P, C, D & HD)
public void SetTitle(String Title) {
this.Title = Title;
}
public void SetFirstName(String FirstName) {
this.FirstName = FirstName;
}
public void SetFamilyName(String FamilyName) {
this.FamilyName = FamilyName;
}
public void SetStudentID(int StudentID) {
this.StudentID = StudentID;
}
public void SetDay(int Day) {
this.Day = Day;
}
public void SetMonth(int Month) {
this.Month = Month;
}
public void SetYear(int Year) {
this.Year = Year;
}
public void SetFirstMark(float FirstMark) {
this.FirstMark = FirstMark;
}
public void SetSecondMark(float SecondMark) {
this.SecondMark = SecondMark;
}
public void SetWeeklyMarks(float WeeklyMarks) {
this.WeeklyMarks = WeeklyMarks;
}
public void SetFinalMark(float FinalMark) {
this.FinalMark = FinalMark;
}
public void SetFinalGrade(String FinalGrade) {
this.FinalGrade = FinalGrade;
}
public void SetOverallMarks(float OverallMarks) {
this.OverallMarks = OverallMarks;
}
public boolean equals(student OtherStudent) {
return (this.FirstName.equalsIgnoreCase(OtherStudent.FirstName)) && (this.FamilyName.equalsIgnoreCase(OtherStudent.FamilyName));
}
//this method is for the calculation of (first and second assignment mark, mark of weekly practical work and exam mark, final mark and overall mark)
public float OverallMarking() {
FirstMarkPercentage = ((FirstMark / 100) * 20);
SecondMarkPercentage = ((SecondMark / 100) * 20);
WeeklyMarksPercentage = ((WeeklyMarks / 10) * 10);
ExamPercentage = ((FinalMark / 100) * 50);
OverallMarks = FirstMarkPercentage + SecondMarkPercentage + WeeklyMarksPercentage + ExamPercentage; //for the overall mark returns
return OverallMarks;
}
//this function arranges the grade calculations and returns the final grade
public String GradeCalculations() {
if (OverallMarks >= 80 && OverallMarks <= 100) { // if grade lies within this range print HD
FinalGrade = "HD";
CounterHD++;
} else if (OverallMarks >= 70 && OverallMarks < 80) { // if grade lies within this range print D
FinalGrade = "D";
CounterD++;
} else if (OverallMarks >= 60 && OverallMarks < 70) { // if grade lies within this range print C
FinalGrade = "C";
CounterC++;
} else if (OverallMarks >= 50 && OverallMarks < 60) { // if grade lies within this range print P
FinalGrade = "P";
CounterP++;
} else if (OverallMarks < 50 && OverallMarks >= 0) { // if grade lies within this range print N
FinalGrade = "N";
CounterN++;
}
return FinalGrade;
}
public void DisplayQuestions() {
System.out.println("\n Welcome to the Menu to perform one of the following operations (You must enter a number between 1-7):");
System.out.println("(1) To add the Student Information.");
System.out.println("(2) To Display the Output from the Average Overall Mark for students.");
System.out.println("(3) To Display all current Student Information.");
System.out.println("(4) To Display the distribution of grades awarded.");
System.out.println("(5) for entering a student ID Number To view all details of the student.");
System.out.println("(6) for entering a student name To view all details of the student.");
System.out.println("(7) Quit");
System.out.println("\n__________________________________________");
}
//This function displays the details of the student with before calculated marks.
public void DisplayOutput() {
System.out.println("\nName: " + GetTitle() + " " + GetFirstName() + " " + GetFamilyName());
System.out.println("Student ID: " + GetStudentID());
System.out.println("Date of Birth: " + GetDay() + "/" + GetMonth() + "/" + GetYear());
System.out.println("Assignment 1 Marks: " + GetFirstMark());
System.out.println("Assignment 2 Marks: " + GetSecondMark());
System.out.println("Weekly Practical Marks: " + GetWeeklyMarks());
System.out.println("Final Exam Marks: " + GetFinalMark());
System.out.println("Final Marks & Grade: " + OverallMarking() + "/" + GradeCalculations());
}
public void addStudent() {
/*Scanner keyboard = new Scanner(System.in);
for (int i = 0; i < list.length; i++) { //for loop is till the student number is achieved
list[i] = new student();
System.out.println("\nTitle of the student (eg, Mr, Miss, Ms, Mrs etc): ");
list[i].SetTitle(keyboard.next());
System.out.println("First name (given name)");
list[i].SetFirstName(keyboard.next());
System.out.println("A last name (family name/surname)");
list[i].SetFamilyName(keyboard.next());
System.out.println("Student number (ID):");
list[i].SetStudentID(keyboard.nextInt());
System.out.println("Enter the Day of birth(1-31): ");
list[i].SetDay(keyboard.nextInt());
System.out.println("Enter the Month of birth (1-12): ");
list[i].SetMonth(keyboard.nextInt());
System.out.println("Enter The Year of birth: ");
list[i].SetYear(keyboard.nextInt());
System.out.println("Students First Assignment Mark (0 - 100): ");
list[i].SetFirstMark(keyboard.nextInt());
System.out.println("Students Second Assignment Mark (0 - 100): ");
list[i].SetSecondMark(keyboard.nextInt());
System.out.println("Enter the mark of Student weekly practical work (0-10) ");
list[i].SetWeeklyMarks(keyboard.nextInt());
System.out.println("Please Enter the Marks for the final Exam(0 - 100): ");
list[i].SetFinalMark(keyboard.nextInt());
System.out.println("- - - - - - - - - - - - -");
System.out.println("Do you want to add another Student? (Yes/No)");
String a = keyboard.next();
if (a.equalsIgnoreCase("yes")) {
addStudent();
} else if (a.equalsIgnoreCase("no")) {
i=list.length+1;
}
}*/
}
}
The array isn't null.
The exception is thrown when you try to call a method on a null member of the array.
You iterate over the full array, but have not necessarily filled the entire array. Members that you have not assigned to reference an object are null.
for (int a = 0; a < list.length; a++) { //To Display all current Student Information.
// list[i] = new student();
list[a].DisplayOutput();
}
One fix would be to stop iterating after you've hit the first null.
for (int a = 0; a < list.length; a++) { //To Display all current Student Information.
// list[i] = new student();
student student = list[a];
if ( null == student ) {
break;
}
else {
list[a].DisplayOutput();
}
}
Another fix would be to remember in case 1 how many students were stored, and change the loop condition to reflect that.
for (int a = 0; a < cntStudents; a++) { //To Display all current Student Information.
By the way, in Java code it is almost universally accepted that:
Class names begin with an uppercase character.
Method names begin with a lowercase character.
I'm relatively new to Java, currently studying it in a night course. I'm having trouble setting the constructor up correctly so that it moves values entered into an array. I have the below code and it seems that the individual fields are being passed correctly but the array is not populated and I can't figure out what I'm doing wrong. I've gone back through my notes, textbooks and checked here. I may just have been staring at it for too long!
import java.util.Scanner;
public class Main {
static Scanner InOut = new Scanner(System.in);
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
//* Declare and initalize variables. Set maximum number of students to 6.
String surname = "", forename = "", course = "a", newCourse, tmpStu ="";
int firstMark = 0, secondMark = 0, thirdMark = 0, finalScore = 0,
option = 0, studentCount = 0, delNum, index = 0;
final int MAXSTUDENT = 6;
Student[] myClass = new Student[MAXSTUDENT];
//* Set class details for the constructor.
while (option != 6) {
//* Call the menu system to be displayed
option = menu();
switch (option) {
//* Checks the value return by the menu for the selected option
case 1:
//* Checks that the maximum number of students has not been exceeded.
if (studentCount >= MAXSTUDENT) {
System.out.println("Maximum number of student entered. \n\n");
menu();
} else {
//* Enter in the student details
InOut.nextLine(); /* ensures that the buffer is cleared*/
System.out.println("Enter student surname: ");
surname = InOut.nextLine();
System.out.println("Enter student forename: ");
forename = InOut.nextLine();
System.out.println("Enter 1st mark: ");
firstMark = InOut.nextInt();
System.out.println("Enter 2nd mark: ");
secondMark = InOut.nextInt();
System.out.println("Enter 3rd mark: ");
thirdMark = InOut.nextInt();
finalScore = 0;
//* Passes the entered paramaters to add the student details to the object class.
//* Increases the student counter by 1.
myClass[studentCount] = new Student(surname, forename, course, firstMark, secondMark, thirdMark, finalScore);
System.out.println(myClass[studentCount]);
studentCount++;
}
break;
case 2:
//* Enter in the student number to be deleted. Number is passed for deletion.
//* Reduces the number of student counter.
System.out.println("Delete which student?");
delNum = InOut.nextInt();
deleteStudent(delNum, studentCount);
studentCount--;
break;
case 3:
//* Allows for the course name to be updated.
InOut.nextLine(); /* ensures that the buffer is cleared*/
System.out.println("Enter new course: ");
newCourse = InOut.nextLine();
Student.setCourse(newCourse);
break;
case 4:
//* Display all details stored in the object class.
for (index = 0; index < studentCount; index = index + 1){
Student.displayDetails(index);
}
break;
case 5:
//* Input the surname of student and this name is passed to
//* display the details for this student only.
InOut.nextLine(); /* ensures that the buffer is cleared*/
System.out.println("Enter surname of student you want to search for: ");
String searchName = InOut.nextLine();
//* searchStudent(myClass, searchName, index, studentCount);
break;
case 6:
//* Exit program
System.out.println("End of program");
break;
default:
System.out.println("Invalid option");
}
}
}
public static int menu() {
//* Display menu options and returns selection.
System.out.println("****Student Menu****");
System.out.println("1. Add new student details");
System.out.println("2. Delete Student");
System.out.println("3. Change Course");
System.out.println("4. Display All Student Details");
System.out.println("5. Search Student by Name");
System.out.println("6. Exit");
System.out.println("\nInput an option:");
int option = InOut.nextInt();
return option;
}
public void addStudent(String surname, String forename, String course, int firstMark, int secondMark, int thirdMark, int finalScore)
//* Accepts passed paramaters of student details and adds them into the object class.
{
System.out.println(surname);
System.out.println(forename);
System.out.println(course);
System.out.println(firstMark);
System.out.println(secondMark);
System.out.println(thirdMark);
System.out.println(finalScore);
}
public static void deleteStudent(int delNum, int studentCount)
//* Accepts student array number to be deleted and displays details of all
//* students still stored.
{
//* int asize = myClass.length, index;
//* for (index = delNum +1; index < asize; index++)
//* {
//* myClass[index-1] = myClass[index];
//* }
//* studentCount --;
}
And this is the Student Constructor being called. I'd added in a few display statements to see if I could find where it was going wrong but no luck. I think it may be to do with the constructor being called from the "static void" main method.
import java.util.Scanner;
public class Student {
private String surname, forename;
private int firstMark, secondMark, thirdMark, finalScore, index;
private int stuCount = 0;
private final int NUMMARK = 3;
private static String course = "French";
Scanner InOut = new Scanner(System.in);
public Student(String surname, String forename, String course, int firstMark, int secondMark, int thirdMark, int finalScore)
{
System.out.println(surname);
this.surname = surname;
this.forename = forename;
this.course = course;
this.firstMark = firstMark;
this.secondMark = secondMark;
this.thirdMark = thirdMark;
finalScore = ((firstMark + secondMark + thirdMark)/ NUMMARK);
this.finalScore = finalScore;
}
public static void setCourse (String newCourse) {
course = newCourse;
}
private String getDetails()
//* Builds student details and returns them to be displayed.
{
String details = "Student Name: " + surname + ", " + forename +"\n";
details = details + "Course Name: " + course + "\n";
details = details + "Student's Marks: " + firstMark + ", " + secondMark + ", " + thirdMark + "\n";
details = details + "Final Mark: " + finalScore + "\n";
return details;
}
public static void displayDetails(int index)
//* Displays all student details that have been entered using the student counter
//* for the number of times to loop.
{
//* if (myClass[index] != null) {
//* System.out.println(myClass[index].getDetails());
//* }
}
}
This
myClass[0] = new Student(surname, forename, course, firstMark, secondMark, thirdMark, finalScore);
studentCount++;
System.out.println(myClass[0]);
Is adding each new student on the previous one, you are always setting the first position of the array, it should be like this:
myClass[studentCount] = new Student(surname, forename, course, firstMark, secondMark, thirdMark, finalScore);
System.out.println(myClass[studentCount]);//BEFORE the counter increment
studentCount++;
Side note:
This code:
System.out.println(myClass[studentCount]);
Will not print the informations that the student contains. In order to print them you have to override the toString method of your Student class, returning the string you want to be printed
your code doesn't have any serious problem. you just have to edit some part of it as follow:
first of all to see the getDeatails() method of your Student class you should declare it as
protected:
so the new version is as follow
protected String getDetails()
{
String details = "Student Name: " + surname + ", " + forename + "\n";
details = details + "Course Name: " + course + "\n";
details = details + "Student's Marks: " + firstMark + ", " + secondMark + ", " + thirdMark + "\n";
details = details + "Final Mark: " + finalScore + "\n";
return details;
}
in the first case what you write is ok. you just have to use the appropriate way to retrieve the data from an array. so use the following code:
//* Passes the entered paramaters to add the student details to the object class.
//* Increases the student counter by 1.
myClass[studentCount] = new Student(surname, forename, course, firstMark, secondMark, thirdMark, finalScore);
for(int i = 0;i<=studentCount;i++){
System.out.println(myClass[i].getDetails());
System.out.println("-----------------------");
}
studentCount++;
System.out.println("now the student count are: "+studentCount);
the following is for case 4:
case 4:
//* Display all details stored in the object class.
System.out.println("studentcount:"+studentCount);
for (index = 0; index < studentCount; index = index + 1) {
System.out.println(myClass[index].getDetails());
System.out.println("---------------------");
}
break;