Create a class Student which is derived from the class Person from
homework 1. The class has the member variables:
facultyNumber - a
String, which will be initialized to value "426789XX" where the XX is
the serial number of the object created in the program (if the program
has created 3 objects, the value of XX respectively will be - 00, 01
and 02).
notes – an array of 20 int values in the interval [2,6]. The
elements of the array will be initialized with the values 1.
and the methods:
void takeExam(int index, int note) - assign the value note
to the element in position index
void failExam(int index) – assign
the value 2 to the element in position index
public String toString ()
- convert the Student to String
i have some thing like this homework and where i m doing mistake i dont know little help i m completely newbie for java
public class Student extends Person {
Student() {
facultyNumber = String.valueOf(Integer.parseInt(facultyNumber) + 1);
System.out.print(" Faculty Number: ");
System.out.print(facultyNumber);
Scanner in = new Scanner(System.in);
System.out.print(" Enter notes: ");
int notes = in.nextInt();
}
Student(String name, int age, String facultyNumber, int notes) {
super(name, age);
}
String facultyNumber = "42678900";
int[] notes ={1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};
void takeExam(int index, int note) {}
void failExam(int index){ Arrays.fill(notes, 2); }
public String toString () {
return "name: " + name + " age: " + age + " Faculty Number: " + facultyNumber +" notes: " + notes ;
}
}
i think i should do some counting for chance faculty no increment but i dont know how to start anybody can help step by step.
Well, a homework question.
public class Student extends Person {
private static final int VALUE_EXAM_FAIL = 2;
private String facultyNumber = "426789XX";
private int[] notes = {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};
//a new object is instantiated from outside this class,
//therefore they have to tell this constructor the facultyNumber (or you use a static facultyNumber)
public Student(int facultyNumber) {
this.facultyNumber = this.facultyNumber.replace("XX", String.valueOf(facultyNumber)); //think about problems if facultyNumber only has 1 digit.
}
public Student(String name, int age, int facultyNumber, int[] notes) {
super(name, age); //what is this?
this(facultyNumber); //and this?
this.notes = notes;
}
public void takeExam(int index, int note) { notes[index] = note; } //what happens here if index = -1 or 99?
public void failExam(int index) { notes[index] = VALUE_EXAM_FAIL; }
#Override
public String toString () {
return "class: " + this.getClass.getSimpleName()
+ " name: " + this.name
+ " age: " + this.age
+ " Faculty Number: " + this.facultyNumber
+ " notes: " + this.notes ; //this could be nicer!
}
}
Use access modifiers like public/private!
This should help you getting started. Think about: should I read from the console here in this class? If yes, how? If no, why not?
i solve my problem like this its working
import java.util.*;
public class Student extends Person {
private static final int VALUE_EXAM_FAIL = 2;
private String facultyNumber = "426789XX";
private int[] notes = {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};
static int index = 0;
private int ind;
Student(){
ind = index;
index++;
this.facultyNumber = this.facultyNumber.replace("XX", String.format("%02d", ind));
Scanner in = new Scanner(System.in);
boolean goodinput = false;
int num = 0;
do {
try {
goodinput = true;
System.out.print("Notes [2,6]:");
num = notes[ind] = Integer.parseInt(in.nextLine());
System.out.println(num);
if ((num < 2) || (num > 6)) {
System.out.println("Input not between 2 and 6, try again.");
goodinput = false;
}
} catch (Exception e) {
System.out.println("Input is not an integer, try again.");
goodinput = false;
}
} while (!goodinput);
}
public Student(String name, int age, int facultyNumber, int[] notes) {
super(name, age);
this.facultyNumber = Integer.toString(facultyNumber);
this.notes = notes;
}
public void takeExam(int index, int note) { notes[ind] = note; }
public void failExam(int index) { notes[ind] = VALUE_EXAM_FAIL; }
#Override
public String toString () {
return super.toString() + " Faculty Number: " + this.facultyNumber
+ " notes: " + this.notes[ind]+ " " + ind;
}
}
Related
I'm creating a Java array of queues program to represent patients in a doctor array. It lets me add nodes in data structure but when I try to print it out it blows up on me. Here is the method
static boolean [] openflag = new boolean[6];
static queue [] Clinic = new queue[6];
static String [] Doctor = {"Doctor 1", Doctor 2", "Doctor 3","Doctor
4","Doctor 5","Doctor 6"};
final static String HEADING = "The clinic moniter of Dylan Rychlik";
static int MAX = 6;
public static void Listpaitents()
{
int queuechoice;
JOptionPane.showMessageDialog(null, "Which doctor would you like to print?");
String InputString = JOptionPane.showInputDialog(null,Doctor, HEADING,
JOptionPane.QUESTION_MESSAGE);
queuechoice = Integer.parseInt(InputString);
if (openflag[queuechoice -1 ] == false){
JOptionPane.showMessageDialog(null, "Sorry, that doctor is notaviable");
}
else{
Paitent[] array = Clinic[queuechoice -1].toArray();
//int size = Clinic[queuechoice -1].getSize();
int limit = Clinic[queuechoice -1].getSize();
//System.out.println(limit);
int x; String out = " Members of the list are: \n";
// boolean exit = false;
for(x = 1; x <= limit; x++) {
out += array[x-1].Print() + "\n";
// System.out.println(array[x-1] + "\n");
}
JOptionPane.showMessageDialog(null,out);
}
}
Here is the toarray() method in queue class.
public static Paitent[] toArray()
{
int x = Length;
Paitent[] Array = new Paitent[Length];
queuenode Current = rear;
for (x = Length; ((Current != null) && (x >= 1));x--)
{
Array[x-1] = new Paitent();
Array[x-1].update(Current.info);
Current = Current.next;
}
return Array;
}
And finally, here is the paitent class
public class Paitent {
protected static String name;
protected static String telephone;
protected static int ID;
//Creates a constructor for a paitent object
public void paitent()
{
name = "";
telephone = " ";
ID = 0;
}
//updates the country object
public void update(Paitent thisThing)
{
name = thisThing.name;
telephone = thisThing.telephone;
ID = thisThing.ID;
}
//asks for user input for country objects
public void input(int i)
{
String PatronHeading = "Country Data Entry";
String entername;
int enterID;
String enterphone;
entername = JOptionPane.showInputDialog(null, "Please Enter the name of
paitent #" + i +": ", PatronHeading, JOptionPane.QUESTION_MESSAGE);
enterphone = JOptionPane.showInputDialog(null, "Please Enter the telephone
number for paitent #" + i +": ", PatronHeading,
JOptionPane.QUESTION_MESSAGE);
String PNumberString = JOptionPane.showInputDialog(null, "Please Enter the
ID for paitent #" + i +": ", PatronHeading, JOptionPane.QUESTION_MESSAGE);
enterID = Integer.parseInt(PNumberString);
name = entername;
telephone = enterphone;
ID = enterID;
}
//prints the results
public String Print()
{
String outputString;
outputString = "Paitent: " + "-" + name + "\n" + " Telephone number " +
telephone + " ID " + ID;
return outputString;
}
//gets and sets the PCI in order to sort them
}
Any help? Tried several tactics to fix it and nothing seems to be working. There a lot of code so if you need the full code please let me know!
A problem with your code is that you are using static variables. This means they can only ever have one value
so change
protected static String name;
protected static String telephone;
protected static int ID;
to
protected String name;
protected String telephone;
protected int ID;
edit and clean up your code
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
Q. Create a class named Participant with fields for a name, age, and street address. Include a constructor that assigns parameter values to each field and a toString() method that returns a String containing all the values.
Also include an equals() method that determines two Participants are equal if they have the same values in all three fields.
Create an application with two arrays of at least 5 Participants each--one holds the Participants in the mini-marathon and the other holds Participants in the diving competition. Prompt the user for Participants who are in both events save the files as Participant.java and TwoEventParticipants.java.*/
Here is my code so far. How do I display the value of Participants who are in both events ?
import javax.swing.JOptionPane;
import java.util.*;
public class TwoEventParticipants {
private static Participant mini[] = new Participant[2];
private static Participant diving[] = new Participant[2];
public static void main(String[] args) {
String name="";;
String add="";
int age=0;
Participant p=new Participant(name, age, add);
Participant p1=new Participant(name, age, add);
setParticipant();
setParticipant1();
displayDetail();
displayDetail1();
//Arrays.sort(p1);
if (p.equals(p1)){
System.out.println(p);
}else{
System.out.println(p1);
}
}
public static void setParticipant(){
for (int x = 0; x < mini.length; x++) {
System.out.println("Enter loan details for customer " + (x + 1) + "...");
//Character loanType=getLoanType();
//String loanType=getLoanType();
String name=getName();
String add=getAdd();
int age=getAge();
System.out.println();
mini[x] = new Participant(name, age, add); //<--- Create the object with the data you collected and put it into your array.
}
}
public static void setParticipant1(){
for (int y = 0; y < diving.length; y++) {
System.out.println("Enter loan details for customer " + (y + 1) + "...");
String name=getName();
String add=getAdd();
int age=getAge();
System.out.println();
diving[y] = new Participant(name, age, add);
}
}
// Participant p=new Participant(name,age,add);
//displayDetails();
// System.out.println( p.toString());
public static void displayDetail() {
// for (int y = 0; y < diving.length; y++) {
System.out.println("Name \tAge \tAddress");
//Participant p=new Participant(name,age,add);
for (int x = 0; x < mini.length; x++) {
System.out.println(mini[x].toString());
// System.out.println(diving[y].toString());
}
}
public static void displayDetail1() {
System.out.println("Name \tAge \tAddress");
for (int y = 0; y < diving.length; y++) {
System.out.println(diving[y].toString());
}
}
public static String getName() {
Scanner sc = new Scanner(System.in);
String name;
System.out.print(" Participant name: ");
return name = sc.next();
}
// System.out.print(" Participant name: ");
// name = sc.next();
public static int getAge() {
int age;
System.out.print(" Enter age ");
Scanner sc=new Scanner(System.in);;
return age= sc.nextInt();
}
public static String getAdd() {
String add;
Scanner sc=new Scanner(System.in);;
System.out.print("Enter Address: ");
return add=sc.next();
}
}
Participant with fields for a name, age, and street address
//
public class Participant {
private String name;
private int age;
private String address;
public Participant(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
#Override
public String toString() {
return name + " " + age + " " + address ;
}
// include an equals() method that determines two Participants are equal
public boolean equals(Participant[] name,Participant[] age,Participant[] add) {
if (this.name.equals(name) && this.address.equals(address)&& age == age){
return true;
}
else{
return false;
}
}
}
This will work for you:
for(Participant p : mini){
if(diving.contain(p)){
System.out.pringtln(p.toString()) ;
}
}
QUESTION: I'm trying to find the win percentage (the formula for win percentage is wins/(wins + loses)). How do I take the values from wins and loses the user enters and add them to my Sysout function. Every time I run the program it displays:
East W L PCT
Braves 45 66 0.000000
Cubs 87 77 0.000000
So what I'm trying to do is get the actual values instead of it saying "0.0000000"
public class Team {
// Data fields...
private int wins;
private int loses;
private String teamName;
private String city;
private String division;
private double winPercentage;
// Getters and setters...
public int getWins() {
return wins;
}
public void setWins(int wins) {
this.wins = wins;
}
public int getLoses() {
return loses;
}
public void setLoses(int loses) {
this.loses = loses;
}
public String getTeamName() {
return teamName;
}
public void setTeamName(String teamName) {
this.teamName = teamName;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getDivision() {
return division;
}
public void setDivision(String division) {
this.division = division;
}
public double getWinPercentage() {
return wins/(wins + loses);
}
public void setWinPercentage(double winPercentage) {
this.winPercentage = winPercentage;
}
}
public class PlayoffSelectorClass extends Team{
public static void main(String[] args) {
List<Team> teams = new ArrayList<Team>();
for (int i = 0; i < 6; i++) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter team name: ");
String name = input.nextLine();
System.out.println("\nPlease enter the city " + name + " played in: ");
String city = input.nextLine();
System.out.println("\nPlease enter the division " + name + " play in: ");
String division = input.nextLine();
System.out.println("\nPlease enter the number of wins " + name + " has: ");
Integer wins = input.nextInt();
System.out.println("\nPlease enter the number of losses " + name + " has: ");
Integer loses = input.nextInt();
if (i < 5) {
System.out.println("\nEnter your next team...\n");
}
Team team = new Team();
team.setTeamName(name);
team.setCity(city);
team.setDivision(division);
team.setWins(wins);
team.setLoses(loses);
team.setWinPercentage(wins / (wins + loses));
teams.add(team);
}
System.out.println("East W L PCT\n");
for (Team team : teams) {
System.out.printf("%s\t%s\t%s\t%f\n",team.getTeamName() + " ", team.getWins() + " " , team.getLoses(), team.getWinPercentage());
}
}
}
The problem is here :
public double getWinPercentage() {
return wins/(wins + loses);
}
You are doing integer division, i.e only keep the int part of the result, and implicitly cast it to a double. So for example if:
wins = 10;
loses = 20;
then winPercentage == 10/30 == 0.33.. and you only keep the 0 and the cast it to double. Hence the 0.0000... etc What you can do instead is:
public double getWinPercentage() {
return wins/(double) (wins + loses);
}