Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
The idea of this program is to calculate the person's weight and age on each planet. and Life class is supposed to be the one who do the calculations and return the values correctly.
my problem is when i run the program it returns 0 ! but I want it to do the calculations and return different values.
Person Class
package solarsystemplanets;
public class Person {
private String name;
public int age;
public double weight;
//Constructors
public Person(String n, int a, double w) {
n = name;
a = age;
w = weight;
}
public Person(){
name = "";
age = 0;
weight = 0;
}
//Setters (Mutator)
public void setName(String n) {
n = name;
}
//Getters (Accessor)
public String getName() {
return name;
}
public int getAge() {
return age;
}
public double getWeight() {
return weight;
}
//PrintDetails Method
public String toString() {
return "Person" + " name=" + name + ", age=" + age + ", weight="
+ weight;
}
}
Life Class
package solarsystemplanets;
public class Life extends Person {
private int earthDays;
public double []surfaceGravity;
public int []planetsDays;
//Constructors
public Life (int e, double []s, int []p){
earthDays = e;
surfaceGravity = s;
planetsDays = p;
}
public Life (int ee){
earthDays = 365;
surfaceGravity = new double[]{0.38,0.91,1.0,0.38,2.34,0.93,0.92,1.12};
planetsDays = new int[]{88,225,365,2,12,29,84,165};
}
public Life(){
this.surfaceGravity = new double[]{0.38,0.91,1.0,0.38,2.34,0.93,0.92,1.12};
this.planetsDays = new int[]{88,225,365,2,12,29,84,165};
}
//Setters (Mutator)
public void setEarthDays(int e) {
earthDays = e;
}
//Getters (Accessor)
public int getEarthDays() {
return earthDays;
}
public double[] getSurfaceGravity() {
double array1[] = new double[surfaceGravity.length];
for(int i =0; i < surfaceGravity.length; i++){
array1[i] = weight * surfaceGravity[i];
}
return array1;
}
public int[] getPlanetsDays() {
int array2[] = new int[planetsDays.length];
for(int i =0; i < planetsDays.length; i++){
array2[i] = (age * getEarthDays())/ planetsDays[i];
}
return array2;
}
//PrintDetails Method
public String toString(int i) {
return "surfaceGravity=" + getSurfaceGravity() + ", planetsDays=" + getPlanetsDays();
}
}
Main
package solarsystemplanets;
import java.util.*;
import java.io.*;
public class SolarSystemPlanets {
public static void main(String[] args) throws IOException {
Person person = new Person();
Life life = new Life();
Planet planet = new Planet();
Scanner input = new Scanner (System.in);
File file = new File ("Solar System Planets");
//User Info
System.out.println("What is Your Name ? ");
person.setName(input.nextLine());
System.out.println("Please Enter Your Age: ");
person.age = input.nextInt();
while (person.age <=0){
System.out.println("error. Please Enter Your Age Again: ");
person.age = input.nextInt();
}
System.out.println("Please Enter Your Weight: ");
person.weight = input.nextInt();
while (person.weight <=0){
System.out.println("error. Please Enter Your Weight Again: ");
person.weight = input.nextInt();
}
for(int i =0; i<planet.planetName.length; i++){
System.out.println(planet.planetName[i]);
System.out.println("Your Weight = " + life.getSurfaceGravity()[i] + "
Your Age = " + life.getPlanetsDays()[i]);
}
}
}
You are setting user inputs on person object and using life object to calculate and print data. As these objects are different fields in life object remains zero.
Life extends Person, so it has inherited person fields. Set all user inputs on life object.
Also, you've forgot to set earthDays on life object.
I am trying to do a program that will convert the input age of a dog into human years, but it doesn't work. Here are the instructions I had for the conversion of the dog years to human years:
A method inHumanYears which will return the age of a pet dog in human years. Here is how to calculate it:
15 human years equals the first year of a medium-sized dog's life.
Year two for a dog equals about nine years for a human.
And after that, each human year would be approximately five years for a dog.
Here a few examples:
a 4-month old dog = 0.25 (which is 1/4 of a year)*15 = 3.75 human years
a 5 years old = 15+9+(5-2) * 5 = 39 human years
So here is what my code looks so far:
import java.util.Scanner;
public class MyPet_1_lab7 {
// Implement the class MyPet_1 so that it contains 3 instance variables
private String breed;
private String name;
private int age;
private double inHumanYears;
// Default constructor
public MyPet_1_lab7()
{
this.breed = null;
this.name = null;
this.age = 0;
}
// Constructor with 3 parameters
public MyPet_1_lab7(String a_breed, String a_name, int an_age){
this.breed = a_breed;
this.name = a_name;
this.age = an_age;
this.inHumanYears = inHumanYears();
}
// Accessor methods for each instance variable
public String getBreed(){
return this.breed;
}
public String getName(){
return this.name;
}
public int getAge(){
return this.age;
}
//Mutator methods for each instance variable
public void setBreed(String a_breed){
this.breed = a_breed;
}
public void setName(String a_name){
this.name = a_name;
}
public void setAge(int an_age){
this.age = an_age;
this.inHumanYears = inHumanYears();
}
// toString method that will return the data in an object formated as per the output
public String toString(){
return (this.breed + " whose name is " + this.name + " and " + (double)this.age + " dog years (" + inHumanYears() + " human years old)");
}
public boolean equals(MyPet_1_lab7 a){
if ((this.breed.equals(a.getBreed())) && (this.age == a.getAge())){
return true;
}
else
return false;
}
public double inHumanYears(){
if ((double)age >= 2 ){
inHumanYears = (15 + 9 + (age - 2))*5;
return (inHumanYears);
}
else {
inHumanYears = age*15;
return (inHumanYears);
}
}
public double getHumanYears(){
double yearOneAge = age >=1 ? 1.0: age;
double yearTwoAge = age >=2 ? 1.0: age > 1? age-1.0: 0.0;
double yearThreeAge = age > 2 ? age-2.0: 0.0;
inHumanYears = yearOneAge * 15 + yearTwoAge*9 + yearThreeAge * 5;
return inHumanYears;
}
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
System.out.print("What type of dog do you have? ");
String breed = keyboard.nextLine();
System.out.print("What is its name? ");
String name = keyboard.nextLine();
System.out.print("How old? ");
int age = keyboard.nextInt();
MyPet_1_lab7 dog= new MyPet_1_lab7();
System.out.println(dog);
MyPet_1_lab7 dog1 = new MyPet_1_lab7(breed,name,age);
System.out.println(dog1);
}
}
'''
The issue is your toString() method accesses a field you set with a method that has not been called. This
public String toString(){
return (this.breed + " whose name is " + this.name + " and "
+ this.age + " dog years (" + inHumanYears + " human years old)");
}
should be changed to invoke inHumanYears(). Like,
public String toString(){
return (this.breed + " whose name is " + this.name + " and "
+ this.age + " dog years (" + inHumanYears() + " human years old)");
}
Your method InHumanYears() is never called + your attribute inHumanYears is never assigned.
You must change your second constructor.
Before :
public MyPet_1_lab7(String a_breed, String a_name, int an_age){
this.breed = a_breed;
this.name = a_name;
this.age = an_age;
}
After :
public MyPet_1_lab7(String a_breed, String a_name, int an_age){
this.breed = a_breed;
this.name = a_name;
this.age = an_age;
this.inHumanYears = inHumanYears();
}
You must also called inHumanYears() in setAge() :
setAge(int age){
this.age = age;
this.inHumanYears = inHumanYears();
}
I obtain this execution (I think your calculation is incorrect):
toto whose name is tata and 3 dog years (125.0 human years old)
your algo seems wrong for the stated requirements.
15 human years equals the first year of a medium-sized dog's life.
Year two for a dog equals about nine years for a human.
And after that, each human year would be approximately five years
for a dog.
also you should change age to allow for decimal points. (if not age may be in months, like the example for your 4month old dog -> in which case you should divide everything by 12). It's usually better to name it ageMonth or ageYear to remove that ambiguity.
you can try breaking each component down.
note: the ?: are ternary operators. Think of it as a "short form" for the if-else statement
public double getHumanYears(){
double yearOneAge = age>=1 ? 1.0: age;
//if age>1, then year1Age=1, otherwise year1Age = age
double yearTwoAge = age>=2 ? 1.0: age>1? age-1.0: 0.0;
//if age>2, then year2Age=2, elseIf age>1, then year2Age = age-1, otherwise, year2Age is 0.
double yearThreeAge = age>2 ? age-2.0: 0.0;
//if age>2, then year3Age= age-2, otherwise, year3Age is 0.
//the formula will break down an age into 3 parts.
//yearOneAge: from 0.0 to 1.0.
//yearTwoAge: from 0.0 to 1.0.
//yearThreeAge: from 0.0 onwards.
//e.g. age=0.8years, year1=0.8, year2=0.0, year3=0.0
//e.g. age=1.5years, year1=1.0, year2=0.5, year3=0.0
//e.g. age=3.6years, year1=1.0, year2=1.0, year3=1.6
inHumanYears = yearOneAge * 15 + yearTwoAge * 9 + yearThreeAge * 5
return inHumanYears;
}
also like Quentin said, you forgot to call getHumanYears in your setter and constructor, or you can update the toString to call getHumanYears().
Ok, so thank you everybody for your time and your help. So here is what I did, I changed the private int age to a double. My friend told me that we didn't need to necessarily put it to an integer. The rest was just change everything to double and it solved all my problem for my output:
import java.util.Scanner;
public class MyPet_1_lab7 {
// Implement the class MyPet_1 so that it contains 3 instance variables
private String breed;
private String name;
private double age; // instead of private int age;
MyPet_1_lab7 dog1;
MyPet_1_lab7 dog2;
// Default constructor
public MyPet_1_lab7()
{
this.breed = null;
this.name = null;
this.age = 0;
}
// Constructor with 3 parameters
public MyPet_1_lab7(String a_breed, String a_name, double an_age){
this.breed = a_breed;
this.name = a_name;
this.age = an_age;
}
// Accessor methods for each instance variable
public String getBreed(){
return this.breed;
}
public String getName(){
return this.name;
}
public double getAge(){
return this.age;
}
//Mutator methods for each instance variable
public void setBreed(String breed2){
this.breed = breed2;
}
public void setName(String name2){
this.name = name2;
}
public void setAge(double age2){
this.age = age2;
}
// toString method that will return the data in an object formated as per the output
public String toString(){
return (this.breed + " whose name is " + this.name + " and " + this.age + " dog years (" + inHumanYears() + " human years old)");
}
public boolean equals(MyPet_1_lab7 a){
if ((this.breed.equals(a.getBreed())) && (this.age == a.getAge())){
return true;
}
else
return false;
}
double human_age = 0;
public double inHumanYears(){
if (this.age < 1)
human_age = (this.age) * 15;
if (this.age >=1 && this.age < 2)
human_age = 15 + (this.age - 1) * 9;
if (this.age >= 2 ){
human_age = 15 + 9 + (age - 2)*5;
}
return human_age;
}
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
System.out.print("What type of dog do you have? ");
String breed = keyboard.nextLine();
System.out.print("What is its name? ");
String name = keyboard.nextLine();
System.out.print("How old? ");
double age = keyboard.nextDouble();
MyPet_1_lab7 dog= new MyPet_1_lab7();
System.out.println(dog);
MyPet_1_lab7 dog1 = new MyPet_1_lab7(breed,name,age);
System.out.println(dog1);
Scanner key = new Scanner(System.in);
System.out.println("\nLet's set up the 1st dog ... ");
System.out.print("\tWhat breed is it? ");
String breed1 = key.nextLine();
System.out.print("\tWhat is the dog's name? ");
String name1 = key.nextLine();
System.out.print("\tHow old is the dog in dog years (a double number)? ");
double age1 = key.nextDouble();
MyPet_1_lab7 dog2 = new MyPet_1_lab7 (breed1, name1, age1);
System.out.println("Dog1 is now a(n) " + dog2);
System.out.println("\nAre the 2 dogs the same breed and age?");
if ((breed.equals(breed1))&& age == age1)
System.out.println("Yes, they are the same breed and age");
else
System.out.println("No, they are not the same breed and/or age");
}
}
'''
This question already has answers here:
How to maintain a Unique List in Java?
(7 answers)
Closed 3 years ago.
Menu Driven java program to take input and display details of the employee. When the user wants to add an employee he chooses option 1 whereas he chooses option 5 to display the details he entered.
I tried the list.contains(Object o) method but it keeps adding the repeated object into the list. Right now I have removed that part of the code.
class Employee {
Scanner sc = new Scanner(System.in);
int empid, num;
String empname, empdesignation, empdept, empproject;
//static ArrayList al = new ArrayList();
public void setEmpNo(int n) {
this.num = n;
}
public int getEmpNo() {
return num;
}
public int getID() {
return empid;
}
public void setID(int id) {
this.empid = id;
}
public String getName() {
return empname;
}
public void setName(String name) {
this.empname = name;
}
public String getDept() {
return empdept;
}
public void setDept(String dept) {
this.empdept = dept;
}
public String getDesig() {
return empdesignation;
}
public void setDesig(String desig) {
this.empdesignation = desig;
}
public String getProject() {
return empproject;
}
public void setProject(String proj) {
this.empproject = proj;
}
public void displayemp(int id, String name, String dept, String designation, String project) {
System.out.print("\n============================================================\n");
System.out.println("ID: " + id);
System.out.println("Name: " + name);
System.out.println("Department: " + dept);
System.out.println("Designation: " + designation);
System.out.println("Project: " + project);
System.out.print("\n============================================================\n");
}
}
public class trying {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int ch = 0, id, n, empID, pid, projectID;
// final int maxEmp=1000;
String name, designation, dept, pname, mgrname, project;
Employee emp10 = new Employee();
Project proj10 = new Project();
List<Employee> list = new ArrayList<Employee>();
List<Project> list1 = new ArrayList<Project>();
// String[] p2=new String[100];
do {
System.out.println("MENU");
System.out.println(
" 1.Add Employee\n 2.Add Project \n 3.Edit Employee\n 4.Edit Project\n 5.Show Employee Deatils \n 6.Show Project Details \n 7.Exit");
// System.out.println("Enter the maximum number of employees: ");
// Employee[] emp=new Employee[maxEmp];
System.out.print("Enter choice: ");
try {
ch = sc.nextInt();
sc.nextLine();
} catch (Exception e) {
System.out.println("Enter an Integer value");
}
switch (ch) {
case 1:
// Employee emp6 = new Employee(1,"qwe","asd","zxc","qazwsxedc");
// Employee emp7 = new Employee(2,"q","d","z","q");
System.out.println("Enter the number of employees to be entered: ");
try {
n = sc.nextInt();
emp10.setEmpNo(n);
if (n < 0) {
System.out.println("Only Positive Numbers & no Letters Please!");
continue;
}
for (int i = 0; i < n; i++) {
Employee emp5 = new Employee();
System.out.print("\n============================================================\n");
System.out.print("Enter ID: ");
id = sc.nextInt();
try {
if (id < 0) {
System.out.println("Enter an Integer value");
continue;
}
emp5.setID(id);
} catch (InputMismatchException e) {
System.out.println("Enter an Integer value");
sc.next();
System.exit(0);
}
sc.nextLine();
System.out.print("Enter Name: ");
name = sc.nextLine();
emp5.setName(name);
System.out.print("Enter Department: ");
dept = sc.nextLine();
emp5.setDept(dept);
System.out.print("Enter Designation: ");
designation = sc.nextLine();
emp5.setDesig(designation);
System.out.print("Enter Project: ");
project = sc.nextLine();
emp5.setProject(project);
System.out.print("\n============================================================\n");
// emp5.displayemp(id, name, dept, designation, project);
list.add(emp5);
// list.add(emp7);
}
}
catch (InputMismatchException e) {
System.out.println("Enter an Integer value");
sc.next(); // this consumes the invalid token
}
case 5:
System.out.println("Showing Employee Details:");
for (Employee e : list) {
System.out.print("\n============================================================\n");
System.out.println("Id: " + e.empid + "\nName: " + e.empname + "\nDept: " + e.empdept + "\nDesig: "
+ e.empdesignation + "\nProject: " + e.empproject);
System.out.print("\n============================================================\n");
}
break;
I want this code to remove the same entries made by the user ie., no redundant entries.
Current output
Id: 1
Name: q
Dept: a
Desig: z
Project: qaz
============================================================
============================================================
Id: 1
Name: q
Dept: a
Desig: z
Project: qaz
============================================================
Expected output
Id: 1
Name: q
Dept: a
Desig: z
Project: qaz
============================================================
list.contains(Object o) needs a bit of extra help before it's willing to find objects in itself. According to this post, ArrayList implements the List interface, which uses equals() to compare two objects; when using contains(), you must have an equals() method defined in your class.
Perhaps something like this:
class Employee {
//...
#Override
public boolean equals(Object o) {
boolean same = true;
if(o != null && o instanceof Employee) {
//check all member variables - remember to use .equals() for string comparison
if(
(this.empId != o.empId) ||
(this.num != o.num) ||
(!(this.empname.equals(o.empname)) ||
(!(this.emdesignation.equals(o.empdesignation)) ||
(!(this.empdept.equals(o.empdept)) ||
(!(this.empproject.equals(o.empproject))
) {
same = false;
}
}
else {
//can't be equal if it's null or not an employee
same = false;
}
return same;
}
}
Once your equals function is defined, you can check if an employee is already in your ArrayList by using list.contains(emp5).
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.
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;
}
}