Main.java
import java.util.*;
public class Main{
static Student[] students = new Student[10];//creates an array of 10 students to be entered
public static int inputThreshold(){
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the Threshold: \n");
int threshold = scan.nextInt();
return Threshold();
}
public static Student inputStudent(){
Scanner scan = new Scanner(System.in);
System.out.println("Enter students surname: \n");//instructs the user to enter a surname
String name = scan.nextLine();//allows the user to input sdtudents surname
System.out.println("Enter student score between 0 and 30: \n");
int score = scan.nextInt();//allows the user to input students score
return new Student(name, score);
}
public static void printStudent(Student student){
int percentage = student.getScore()*10/3;//retrieves the percentage of the score submitted out of 30
System.out.println("Surname: " + student.getName() + " Score: " + student.getScore() + " Percentage: " + percentage + "%");
//prints out the surname, score and percentage achieved by the student
}
public static void printThreshold(int threshold){
int percentage = student.getScore()*10/3;//retrieves the percentage of the score submitted out of 30
if (percentage < threshold){
System.out.println("Surname: " + student.getName() + " Score: " + student.getScore() + " Percentage: " + percentage + "%");
//prints out the surname, score and percentage achieved by the student
}
}
public static Student getWinner(Student[] student){
Student x = student[0];
for(int i = 1; i < 10; i++){
if(student[i].getScore() > x.getScore()){
x = student[i];
}
}
return x;
}
public static void main(String[] args){
for (int i = 0; i = 1; i++){
threshold = inputThreshold;
}
for (int i = 0; i < 10; i++){
students[i] = inputStudent();
}
for(int i = 0; i < 10; i++){
printStudent(students[i]);
}
for(int i= 0; i < 1; i++){
printThreshold(students[i]);
}
Student winrar = getWinner(students);//retrieves the winner from getWinner into a variable
System.out.println("AND WE HAVE OUR WINNER! \n" + "Name: " + winrar.getName() + " Score: " + winrar.getScore());
//prints out the highest scoring students surname, with their score
}
}
Student.java
public class Student{
private String name;//sets name to characters
private int score;//sets score to numbers
private int threshold;//sets the threshold of the score
private int max = 30;//sets max score to 30
public Student(String name, int score){
this.name = name;
if (score <= max && score >= 0) //if the score is equal to 30 or less than 0
this.score = score;//the score can be stored
else{
System.out.println("This number is too big ");//if it is larger than 30 it cannot be stored and shows errors message
System.exit(1);//this will end the program
}
}
public String getName(){
return name;
}
public int getScore(){
return score;
}
public int getThreshold(){
return threshold;
}
public void setScore(int s){
this.score = s;
}
public void setName(String n){
this.name = n;
}
public void setThreshold(int t){
this.threshold = t;
}
}
Is returns Cannot Find Symbol - method Threshold()
I'm not sure what to refer to or how to call the method to get it to run correctly. Brief: 10 users, 10 scores. There's a threshold to be achieved by each entrant. The program outputs their names, scores achieved and the percentage of their score. But it should also announce the overall winner.
Not sure here
return Threshold();
should be
return threshold;
change Threshold() to threshold.
I strongly advice you to read this article before writing another program
Objects, Instance Methods, and Instance Variables
public static int inputThreshold(){
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the Threshold: \n");
int threshold = scan.nextInt();
return Threshold();
}
public static void main(String[] args){
for (int i = 0; i = 1; i++){
threshold = inputThreshold;
}
...rest of code in main
}
threshold is a local variable defined in inputStudent(), you can't access it in main() .Also return Threshold();, there is no Threshold() method defined in the code you've provided
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.
I'm practicing 2d array and stumbled upon on how to reiterate the inside loop of array to accept another set of inputs. I got stuck on how to reiterate the inputs without sacrificing the reinitialization of the loop variable so that it will not reset the index pointer of the array.
Here's the main class:
public class Games {
public static void main(String args[]) {
GamesClass data = new GamesClass();
List output[][] = data.createlist();
data.print(output);
}
}
class List {
private String Gamers, Status;
private int Score;
public List()
{
Gamers = "";
Score = 0;
Status = "";
}
public List(String name, int score, String status)
{
Gamers = name;
Score = score;
Status = status;
}
public void setGamers(String name)
{
Gamers = name;
}
public String getGamers()
{
return Gamers;
}
public void setScores(int score)
{
Score = score;
}
public int getScores()
{
return Score;
}
public void setStatus(String status)
{
Status = status;
}
public String getStatus()
{
return Status;
}
}
And here's the invoking class:
import java.util.*;
class GamesClass {
private int ngames,ngamers;
private String[] games;
public void nloops()
{
Scanner in = new Scanner(System.in);
System.out.print("Enter no. of games: ");
ngames = in.nextInt();
System.out.print("Enter number of gamers each game: ");
ngamers = in.nextInt();
games = new String[ngames];
}
public String[] inputgames()
{
Scanner in = new Scanner(System.in);
for(int i=0 ; i<ngames ; ++i)
{
System.out.print("Enter Game: ");
games[i] = in.next();
}
return games;
}
public List[][] createlist()
{
nloops();
inputgames();
List[][] list = new List[ngames*ngamers][3];
Scanner in = new Scanner(System.in);
int score, n, i=0;
for(n=0 ; n<ngames ; ++n)
{
System.out.println("\nGame#" + (n+1) + " " + games[n]);
for(; i<list.length/ngames ; ++i)
{
list[i][0] = new List();
System.out.print("Gamer " + (i+1) + ": ");
list[i][0].setGamers(in.next());
System.out.print("Score: ");
score = in.nextInt();
list[i][0].setScores(score);
if(score>=1 && score<=50) list[i][0].setStatus("Noob");
else if(score>=51 && score<=100) list[i][0].setStatus("Savage");
else if(score>=101 && score<=150) list[i][0].setStatus("Expert");
else if(score>=151 && score<=200) list[i][0].setStatus("Master");
else if(score>=201 && score<=250) list[i][0].setStatus("Veteran");
else if(score>=251 && score<=300) list[i][0].setStatus("Legendary");
}
i+=ngamers;
}
return list;
}
public void print(List[][] value)
{
int n, i=0;
for(n=0 ; n<ngames ; ++n)
{
System.out.println("\nGame#" + (n+1) + " " + games[n]);
System.out.println("\nGamer\t\tScore\t\tStatus");
for( ;i<value.length/ngames ; ++i)
{
System.out.println((i+1) + " " + value[i][0].getGamers() + "\t\t" + value[i][0].getScores() + "\t\t" + value[i][0].getStatus());
}
i+=ngamers;
}
}
}
The output keeps stucked after inputting the first set of inputs.
Enter no. of games: 2
Enter number of gamers each game: 2
Enter Game: VALORANT
Enter Game: LOL
Game#1 VALORANT
Gamer 1: Jrk
Score: 100
Gamer 2: Dash
Score: 200
Game#2 LOL
Game#1 VALORANT
Gamer Score Status
1 Jrk 100 Savage
2 Dash 200 Master
Game#2 LOL
Gamer Score Status
Change the condition in the loop from
i < list.length/ngames
to i < (list.length/ngames)*(n+1) and also remove this line at the end of the loop : i+=ngamers; The variable is being incremented in the loop itself, there's no need to change it again.
However, this will produce the output
Game#1 VALORANT
Gamer 1: Jrk
Score: 100
Gamer 2: Dash
Score: 200
Game#2 LOL
Gamer 3 : name
Score : 300
Gamer 4 : name2
Score : 400
If you want to display Gamer 1 and Gamer 2 for the second game as well, print (i - n*ngamers + 1) instead of just (i+1)
Make these same changes to the print function as well
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.
How can I get the overriden method calculateResult() to work correctly in my StudentTest class? I need total in calculateResult() to be the total that was calculated in StudentTest from the users input. Or do I have my code for user input in the wrong class?
Student class
public class Student {
// Data Members
private String name;
private int idNumber;
private int examResult;
// Constructor
public Student() {
name = "Unassigned";
idNumber = 0;
examResult = 0;
}
// Getters
public String getName(){
return name;
}
public int getIdNumber(){
return idNumber;
}
public int getExamResult(){
return examResult;
}
// Setters
public void setName(String name){
this.name = name;
}
public void setIdNumber(int idNumber){
this.idNumber = idNumber;
}
public void setExamResult(int examResult){
this.examResult = examResult;
}
// Calculate Result
public void calculateResult() {
int total = 0;
int result = (total / 5);
// Check if Student passed or failed
if (result < 0) {
System.out.println("Overall Result: " + result + " (Fail)");
} else {
System.out.println("Overall Result: " + result + " (Pass)");
}
}
} // end class
Undergraduate class
public class Undergraduate extends Student {
public Undergraduate(){
super();
}
// Method to Calculate Result
#Override
public void calculateResult() {
int total = 0; // Want this total to be the total in StudentTest
int result = (total / 5);
// Check if Student passed or failed
if (result < 50) {
System.out.println("Overall Result: " + result + " (Fail)");
} else {
System.out.println("Overall Result: " + result + " (Pass)");
}
} // end method
} // end class
Postgraduate class
public class Postgraduate extends Student{
public Postgraduate(){
super();
}
// Method to Calculate Result
#Override
public void calculateResult() {
int total = 0; // Want this total to be the total in StudentTest
int result = (total / 5);
// Check if Student passed or failed
if (result < 40) {
System.out.println("Overall Result: " + result + " (Fail)");
} else {
System.out.println("Overall Result: " + result + " (Pass)");
}
} // end method
} // end class
StudentTest class
import java.util.Scanner;
public class StudentTest {
public static void main(String [] args){
// Declaration & Creation of Scanner object
Scanner input = new Scanner(System.in);
// Create Array of Undergrad and Postgrad Students
Student[] students = new Student[5];
students[0] = new Undergraduate();
students[1] = new Postgraduate();
students[2] = new Undergraduate();
students[3] = new Postgraduate();
students[4] = new Undergraduate();
// Get Input for Name
for (int i = 0; i < students.length; i++) {
System.out.println();
System.out.print("Enter Student Name: ");
students[i].setName(input.nextLine());
// Get Input for Id Number
System.out.print("Enter Student ID Number: ");
students[i].setIdNumber(input.nextInt());
input.nextLine();
// Initialise Variables
int examsEntered = 0;
int total = 0;
// Get Input for Exam Result and add to total
while (examsEntered < 5) {
System.out.print("Enter Exam Result (0-100): ");
students[i].setExamResult(input.nextInt());
input.nextLine();
if (students[i].getExamResult() >= 0 && students[i].getExamResult() <= 100) {
total = total + students[i].getExamResult(); // This is the total I want in my calculateResult method
examsEntered = examsEntered + 1;
} else {
System.out.println("Please Enter a Valid Number 0-100");
}
}
}
for (int i = 0; i < students.length; i++) {
// Display Student Info and Results
System.out.println();
System.out.println("Student Name: " + students[i].getName());
System.out.println("Student ID: " + students[i].getIdNumber());
students[i].calculateResult();
System.out.println();
}
} // end main
} // end class
Can't understand what you're trying to achieve. Are you trying to calculate an average score per student or an average score for all students?
You also can't access a variable (total) from outside your class student (and all overriden classes) without having a reference on it.
Here what i propose :
public class Student {
// Data Members
private String name;
private int idNumber;
private List<Integer> examResults;
// Constructor
public Student() {
name = "Unassigned";
idNumber = 0;
examResults = new ArrayList<Integer>(5);
}
// Getters
public String getName(){
return name;
}
public int getIdNumber(){
return idNumber;
}
public void addResult(Integer result){
examResults.add(result);
}
// Setters
public void setName(String name){
this.name = name;
}
public void setIdNumber(int idNumber){
this.idNumber = idNumber;
}
// Calculate Result
protected Integer calculateResult() {
Integer total = 0;
for(Integer result : examResults){
total += result;
}
return total / examResults.size();
}
public void showResultText(){
Integer result = calculateResult();
// Check if Student passed or failed
if (result < 0) {
System.out.println("Overall Result: " + result + " (Fail)");
} else {
System.out.println("Overall Result: " + result + " (Pass)");
}
}
}
public class Undergraduate extends Student {
#Override
public void showResultText() {
Integer result = calculateResult();
if (result < 50) {
System.out.println("Overall Result: " + result + " (Fail)");
} else {
System.out.println("Overall Result: " + result + " (Pass)");
}
}
}
public class Postgraduate extends Student {
#Override
public void showResultText() {
Integer result = calculateResult();
if (result < 40) {
System.out.println("Overall Result: " + result + " (Fail)");
} else {
System.out.println("Overall Result: " + result + " (Pass)");
}
}
}
public class StudentTest {
public static void main(String [] args){
// Declaration & Creation of Scanner object
Scanner input = new Scanner(System.in);
// Create Array of Undergrad and Postgrad Students
Student[] students = new Student[5];
students[0] = new Undergraduate();
students[1] = new Postgraduate();
students[2] = new Undergraduate();
students[3] = new Postgraduate();
students[4] = new Undergraduate();
// Get Input for Name
for (Student student : students) {
System.out.println();
System.out.print("Enter Student Name: ");
student.setName(input.nextLine());
// Get Input for Id Number
System.out.print("Enter Student ID Number: ");
student.setIdNumber(input.nextInt());
input.nextLine();
// Initialise Variables
int examsEntered = 0;
// Get Input for Exam Result and add to total
while (examsEntered < 5) {
System.out.print("Enter Exam Result (0-100): ");
Integer result = input.nextInt();
input.nextLine();
if (result >= 0 && result <= 100) {
student.addResult(result);
examsEntered++;
} else {
System.out.println("Please Enter a Valid Number 0-100");
}
}
}
for (Student student : students) {
// Display Student Info and Results
System.out.println();
System.out.println("Student Name: " + student.getName());
System.out.println("Student ID: " + student.getIdNumber());
student.showResultText();
System.out.println();
}
} // end main
}
It has to do with that your code did not "save" the value for the total.
I will recommend that
you have a int array for examResults
and then in your calculateResult method, sum up the total to determine the average
be mindful of the integer division issue
The .txt file looks like this:
Gator Ali 85
Vator Ella 75
Beam James 95
Lastin Class 55
I've seen other people trying to get similar code on here, but none of that helped.
I can get the average; however, I also need to print out if the score 10 points below average.
Here is my output:
run:
Welcome to the Student Scores Application.
Ali Gator 85
Ella Vator 75
James Beam 95
Class Lastin 55
Beam, James: 95
Gator, Ali: 85
Lastin, Class: 55
Vator, Ella: 75
Your score is 10 points or more below the class average
Class Average: 77.5
Here is my code:
public static void main(String[] args) throws Exception {
Scanner aScanner = new Scanner(new FileReader("src//chapt11//Studentdata.txt"));
System.out.println("Welcome to the Student Scores Application.\n");
int nStudent = 100;
Student[] studentArray = new Student[nStudent];
int counter = 0;
while (aScanner.hasNext()) {
String lastName = aScanner.next();
String firstName = aScanner.next();
int score = aScanner.nextInt();
System.out.println(firstName + " " + lastName + " " + score);
studentArray[counter++] = new Student(lastName, firstName, score);
Arrays.sort(studentArray, 0, counter);
}
System.out.println();
for(int j = 0; j < counter; j++){
System.out.println(studentArray[j]);
}
double sum = 0;
for(int j = 0; j < counter; j++){
sum += studentArray[j].getExamScore();
}
double average = (sum*1.0)/counter;
for(int j = 0; j < counter; j++){
int score = studentArray[j].getExamScore();
if (score <= (average - 10)){
System.out.println("Your score is 10 points or more below the class average");
}
}
System.out.println();
System.out.println("Class Average: " + average);
System.out.println();
aScanner.close();
}
class Student implements Comparable<Student> {
private String firstName;
private String lastName;
private int score;
public Student(String firstName, String lastName, int score) {
this.firstName = firstName;
this.lastName = lastName;
this.score = score;
}
public int getExamScore() {
return score;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
#Override
public int compareTo(Student s) {
if(!firstName.equalsIgnoreCase( s.firstName)) {
return firstName.compareToIgnoreCase(s.firstName);
}
if(!lastName.equalsIgnoreCase(s.lastName)) {
return lastName.compareToIgnoreCase(s.lastName);
}
return score - s.score;
}
#Override
public String toString(){
return firstName + ", " + lastName + ": "+ score;
}
}
I see some problems with your code.
Firstly, there is no need to call Arrays.sort every time you add a Student to the studentArray. Place this method call outside the end of while which sorts complete array with just one call to the method.
Secondly, and more importantly, how do you want the Student objects compared?
The compareTo method inside Student doesn't make sense. If you want the students to be sorted only by their scores you should have something like this:
#Override
public int compareTo(Student s) {
return this.score - s.score;
}
And as far as the expected output is concerned, this is what's happening.
The following line prints each Student as they are added to the array:
System.out.println(firstName + " " + lastName + " " + score);
This part prints each Student object again:
for (int j = 0; j < counter; j++) {
System.out.println(studentArray[j]);
}
And this line gets printed only when score <= (average - 10) evaluates to true:
System.out.println("Your score is 10 points or more below the class average");
I believe now you see the problem.