3 separate ArrayList - java

ACME wants to layoff some employees. Using three ArrayLists, form three lists of employees. The first list will contain all the programmers, the second all the non-programming people making over one hundred thousand dollars, and the last all other people. Using separate loops print out the contents of each ArrayList. (The following are what I did, but not work... looking for help)
import java.util*;
class Employee
{
private String name;
private String address;
private String position;
private double salary;
private String getName()
{return name;}
public String getAddress()
{return address;}
public double getPosition()
{return position;}
public double getSalary()
{return salary;}
public void setName(String aName)
{name=aName;}
public void setAddress(String aAddress)
{address=aAddress;}
public void set(double aPosition)
{postion=aPosition;}
public void setSalary(double aSalary)
{salary=aSalary;}
public employee(String aName, String aAddress, double aPosition; double aSalary)
{
name=aName;
address=aAddress;
position=aPosition;
Salary=aSalary; }
public String toString()
{return name+address+position+salary;}
}
class employee
{public static void main(String[] args)
{Scanner in = new Scanner(System.in);
Employee[] Newemp=new Car[500];
for(int i=0, i<Newemp.length;i++)
{System.out.print(“Enter the name”);
String name=in.nextLine();
System.out.print(“Enter the address”);
String address=in.nextLine();
System.out.print(“Enter the position”);
double position=in.nextDouble();
System.out.print(“Enter the salary”);
double salary=in.nextInt() ;
in.nextLine();
Newemp[i]=new Employee(name, address, position, salary);
}
ArrayList<Employee>programmers=new ArrayList<Employee>();
ArrayList<Employee>nonprogrammers=new ArrayList<Employee>();
ArrayList<Employee>others=new ArrayList<Employee>();
for(int i=0; i<Newemp.salary; i++)
{if(Newemp[i]. getposition().equals(“programmer”))
programmers.add(Newemp[i]);
else if(Employee[i].getsalary()>100000
nonprogrammers.add(Newemp[i]);
else
others.add(Newemp[i]);
}
for(int i=0; i<programmer.();i++)
{
Employee<=programmer.get(i);
System.out.println(i);
}}}

i think this will help
for (int i = 0; i < Newemp.length; i++) {
if (Newemp[i].getPosition().equals("programmer")){
programmers.add(Newemp[i]);
System.out.println("programmers"+programmers);
}
else if (Newemp[i].getSalary()> 100000)
{
nonprogrammers.add(Newemp[i]);
System.out.println("salary 100000 thousand"+nonprogrammers);
} else{
others.add(Newemp[i]);
System.out.println("others"+others);
}
}
for (int i = 0; i < programmers.size(); i++) {
EmployeeData aa= programmers.get(i);
System.out.println("All aaray"+aa);
}

in your main()
for(int i=0; i < Newemp.salary; i++)
...
else if(Employee[i].getsalary()>100000
should be:
for(int i=0; Newemp[i] != null; i++)
...
else if([i].getsalary()>100000)

I hope you understand the concept of object, the methods & variables available with the array can not be mixed with others and vice-versa. length is a variable inside the array object which returns you the size. I would suggest instead of declaring a huge array and then iterating through it. Directly add your objects into an ArrayList as given below. I hope it helps.
import java.util.ArrayList;
import java.util.Scanner;
public class Employee {
private String name;
private String address;
private String position;
private double salary;`
public Employee(String aName, String aAddress, String aPosition,
double aSalary) {
name = aName;
address = aAddress;
position = aPosition;
salary = aSalary;
}
private String getName() {
return name;
}
public String getAddress() {
return address;
}
public String getPosition() {
return position;
}
public double getSalary() {
return salary;
}
public void setName(String aName) {
name = aName;
}
public void setAddress(String aAddress) {
address = aAddress;
}
public void set(String aPosition) {
position = aPosition;
}
public void setSalary(double aSalary) {
salary = aSalary;
}
public String toString() {
return name + address + position + salary;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int maxSize = 500;
ArrayList<Employee> programmers = new ArrayList<Employee>();
ArrayList<Employee> nonprogrammers = new ArrayList<Employee>();
ArrayList<Employee> others = new ArrayList<Employee>();
for (int i = 0; i < maxSize; i++) {
System.out.println("Enter the name");
String name = in.nextLine();
System.out.print("Enter the address");
String address = in.nextLine();
System.out.print("Enter the position");
String position = in.nextLine();
System.out.print("Enter the salary");
double salary = in.nextInt();
in.nextLine();
Employee newEmployee = new Employee(name, address, position, salary);
if (position.equals("programmer"))
programmers.add(newEmployee);
else if (salary > 100000)
nonprogrammers.add(newEmployee);
else
others.add(newEmployee);
}
}
}

Related

Cant change method's variables in Java objects

I have a problem with changing variable value in contact object. I'm trying to make a contact list but I can't change value of variables trought methods. I have editContact method which calls changeName method, both methods are passed ArrayList object trought reference so it shouldn't have problems with changing values trought ArrayList in main method, but problem is when I want to change object's name it won't change it. Is there something I'm missing here?
package telefonski_imenik;
public class Contact {
protected String name;
protected String lastname;
protected String number;
public Contact(String name, String lastname, String number) {
setName(name);
setLastName(lastname);
setNumber(number);
}
public void setName(String name) {
this.name = name;
}
public void setLastName(String lastname) {
this.lastname = lastname;
}
public void setNumber(String number) {
this.number = number;
}
public String getName() {
return this.name;
}
public String getLastName() {
return this.lastname;
}
public String getNumber() {
return this.number;
}
}
package telefonski_imenik;
import java.util.ArrayList;
import java.util.Scanner;
public class TelefonskiImenik {
public static void createContact(String ime, String prezime, String broj, ArrayList<Contact>
ContactList) {
Contact noviKontakt = new Contact(ime, prezime, broj);
ContactList.add(noviKontakt);
}
public static void editContact(ArrayList<Contact> ContactList) {
System.out.println("Unesite nove podatke");
changeName(ContactList);
}
public static void changeName(ArrayList<Contact> ContactList) {
Scanner novinput = new Scanner(System.in);
System.out.println("Unesite staro ime");
String oldName = novinput.nextLine();
System.out.println("Unesite novo ime");
String newName = novinput.nextLine();
for (int i = 0; i < ContactList.size(); i++) {
if (ContactList.get(i).equals(oldName)) {
ContactList.get(i).setName(newName);
}
}
novinput.close();
}
public static void main(String[] args) {
ArrayList<Contact> ContactList = new ArrayList<Contact>();
Scanner input = new Scanner(System.in);
System.out.println("Unesite podatke");
String name = input.nextLine();
String lastname = input.nextLine();
String number= input.nextLine();
createContact(name, lastname, number, ContactList);
for (int i = 0; i < ContactList.size(); i++) {
System.out.println(ContactList.get(i).getName());
System.out.println(ContactList.get(i).getLastName());
System.out.println(ContactList.get(i).getNumber());
}
editContact(ContactList);
for (int i = 0; i < ContactList.size(); i++) {
System.out.println(ContactList.get(i).getName());
System.out.println(ContactList.get(i).getLastName());
System.out.println(ContactList.get(i).getNumber());
}
input.close();
}
}
You forgot to get the name of the object in your loop:
for (int i = 0; i < ContactList.size(); i++) {
if (ContactList.get(i).equals(oldName)) {
ContactList.get(i).setName(newName);
}
}
ContactList.get(i).getName().equals(oldName)

How do I assign object from one class to another class and how do I calculate double and int inside an ArrayList?

I have an assignment but i have problem trying to do some part of it. Appreciate if anyone can give me a hand.
Assignment brief: https://pastebin.com/3PiqvfTE
Main Method: https://pastebin.com/J2kFzB3B
import java.util.ArrayList;
import java.util.Scanner;
public class mainMethod {
public static void main(String[] args) {
//scanner
Scanner scanner = new Scanner (System.in);
//subject object
Subject subject = new Subject (0,null,0);
System.out.println("How many subject do you want to enter: ");
int subjectNumber = scanner.nextInt();
for (int j = 0; j < subjectNumber; j++) {
//subject ID
System.out.println("Please enter the subject ID: ");
int subID = scanner.nextInt();
//subject Name
System.out.println("Please enter subject name: ");
String subName = scanner.next();
//subject fee
System.out.println("Please enter subject fee: ");
double subFee = scanner.nextDouble();
//add subject
subject.addSubject(subID, subName, subFee);
}
//display subject
System.out.println(subject.getSubject());
/*
//loop for part time teacher
System.out.println("Please enter how many part time teacher do you have: ");
int PTcounter = scanner.nextInt();
for (int i = 0; i < PTcounter; i++) {
*/
Teacher teach = new Teacher (0,null,null);
//teacher employee ID
System.out.println ("Please enter the teacher employee ID: ");
int tid = scanner.nextInt();
//teacher name
System.out.println("Please enter the teacher name: ");
String tname = scanner.next();
//teacher gender
System.out.println("Please enter the teacher gender: ");
String tgender = scanner.next();
//add teacher details
teach.addTeacher(tid, tname, tgender);
//display teacher details
System.out.println(teach.getTeacher());
//call address class
Address address = new Address (0,null,null,0);
//address house number
System.out.println("Please enter house number: ");
int addyNum = scanner.nextInt();
//address street name
System.out.println("Please enter street name: ");
String StreetName = scanner.next();
//address city
System.out.println("Please enter city: ");
String City = scanner.next();
//address post code
System.out.println("Please enter postcode: ");
int Postcode = scanner.nextInt();
//add address
address.addAddress(addyNum, StreetName, City, Postcode);
//display address
System.out.println(address.getAddress());
//call Part Time Salary class
PartTimeSalary ptSalary = new PartTimeSalary(0,0);
//max hours
System.out.println("Please enter maximum work hours: ");
int maxHours = scanner.nextInt();
//hourly rate
System.out.println("Please enter hourly rate: ");
double hourlyRate = scanner.nextDouble();
ptSalary.addPTSalary(maxHours, hourlyRate);
System.out.println(ptSalary.getHourlyRate());
//System.out.printf("Teacher details is %s, Subject details is %s, Address is %s", teach.toString(),subject.toString(),address.toString());
}
}
1st problem. I have a subject class and a teacher class. Teacher will be able to teach maximum of 4 subject. I have prompt user to enter subject details before entering teacher details, so when user enter teacher details they will be able to assign subject to teacher just by using the subjectID. I have problem implementing this. My subject is already store in an ArrayList but how to I connect this with teacher. And in the end the program will display what subject each teacher teaches.
Subject Class: https://pastebin.com/iBYFqYDN
import java.util.ArrayList;
import java.util.Arrays;
public class Subject {
private int subjectID;
private String subjectName;
private double fee;
private ArrayList <Subject> subjectList = new ArrayList <Subject>();
public Subject(int subjectID, String subjectName, double fee) {
this.subjectID = subjectID;
this.subjectName = subjectName;
this.fee = fee;
}
public int getSubjectID () {
return subjectID;
}
public void setSubjectID (int subjectID) {
this.subjectID = subjectID;
}
public String getSubjectName () {
return subjectName;
}
public void setSubjectName (String subjectName) {
this.subjectName = subjectName;
}
public double getFee () {
return fee;
}
public void setFee (double fee) {
this.fee = fee;
}
#Override
public String toString() {
return "[subjectID=" + subjectID + ", subjectName=" + subjectName + ", fee=" + fee + "]";
}
public void addSubject (int subjectID, String subjectName, double fee) {
subjectList.add(new Subject(subjectID, subjectName, fee) );
}
public String getSubject () {
return Arrays.toString(subjectList.toArray());
}
}
Teacher class: https://pastebin.com/Np7xUry2
import java.util.ArrayList;
import java.util.Arrays;
public class Teacher {
private int employeeID;
private String name;
private String gender;
private ArrayList <Teacher> teacherDetailsList;
public Teacher (int employeeID, String name, String gender) {
this.employeeID = employeeID;
this.name = name;
this.gender = gender;
this.teacherDetailsList = new ArrayList <Teacher>();
}
public int getEmployeeID () {
return employeeID;
}
public void setEmployeeID (int employeeID) {
this.employeeID = employeeID;
}
public String getName () {
return name;
}
public void setName (String name) {
this.name = name;
}
public String getGender () {
return gender;
}
public void setGender (String gender) {
this.gender = gender;
}
#Override
public String toString() {
return "[employeeID=" + employeeID + ", name=" + name + ", gender=" + gender + "]";
}
public void addTeacher (int employeeID, String name, String gender) {
teacherDetailsList.add(new Teacher (employeeID,name,gender));
}
public String getTeacher () {
return Arrays.toString(teacherDetailsList.toArray());
}
}
2nd problem. Teacher will either be part time or full time teacher. Part time teacher will have a maximum work hour they can work and an hourly rate they will be paid for, so the final salary of part time teacher will be "maximum hours" multiply by "hourly rate". I have store "hourly rate" and "maximum work hours" in an ArrayList but how do I call them to make the multiplication then displaying at the end.
Part time salary class: https://pastebin.com/iGKpu87Y
import java.util.ArrayList;
public class PartTimeSalary {
private int maxHour;
private double hourlyRate;
private double hourlySalary;
private ArrayList <PartTimeSalary> PTSalary = new ArrayList <PartTimeSalary>();
private ArrayList <Double> finalHourlySalary = new ArrayList <Double>();
public PartTimeSalary (int maxHour, double hourlyRate) {
this.maxHour = maxHour;
this.hourlyRate = hourlyRate;
}
public int getMaxHours () {
return maxHour;
}
public void setMaxHour (int maxHour) {
this.maxHour = maxHour;
}
public double getHourlyRate () {
return hourlyRate;
}
public void setHourlyRate (double hourlyRate) {
this.hourlyRate = hourlyRate;
}
public double getHourlySalary() {
hourlySalary = hourlyRate*maxHour;
return hourlySalary;
}
public void addPTSalary (int maxHour, double hourlyRate) {
PTSalary.add(new PartTimeSalary(maxHour,hourlyRate));
}
public void FinalHourlySalary (double hourlySalary) {
hourlySalary = hourlyRate * maxHour;
finalHourlySalary.add(hourlySalary);
}
public ArrayList<Double> getFinalSalary () {
return (new ArrayList <Double>());
}
}
3rd question. I have an address class which is suppose to be part of the Teacher class. I can't seem to connect the address class with teacher class.
Address class: https://pastebin.com/s2HN5p80
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Address {
private int houseNum;
private String streetName;
private String city;
private int postcode;
private List <Address> address = new ArrayList <Address>();
public Address (int houseNum, String streetName, String city, int postcode) {
this.houseNum = houseNum;
this.streetName = streetName;
this.city = city;
this.postcode = postcode;
}
public int getHouseNum() {
return houseNum;
}
public void setHouseNum (int houseNum) {
this.houseNum = houseNum;
}
public String getStreetName() {
return streetName;
}
public void setStreetName (String streetName) {
this.streetName = streetName;
}
public String getCity() {
return city;
}
public void setCity (String city) {
this.city = city;
}
public int getPostcode() {
return postcode;
}
public void setPostcode (int postcode) {
this.postcode = postcode;
}
public void addAddress (int houseNum, String streetName, String city, int postcode) {
address.add(new Address (houseNum,streetName,city,postcode));
}
#Override
public String toString() {
return "[houseNum=" + houseNum + ", streetName=" + streetName + ", city=" + city + ", postcode="
+ postcode + "]";
}
public String getAddress () {
return Arrays.toString(address.toArray());
}
}
Thank you 😃😊
Question 1)
Put the "teacherDetailsList" and "subjectList" ArrayLists in the main method, not the consructors. Add the teachers and subjects in main methods, not constructors.
Add a new ArrayList called "mySubjects" as a field for the Teacher Class
Add the following 2 method to the Teacher class:
public Teacher (int employeeID, String name, String gender, ArrayList<Subject> s) {
this.employeeID = employeeID;
this.name = name;
this.gender = gender;
this.mySubjects=s;
}
public Teacher (int employeeID, String name, String gender, Subject s) {
this.employeeID = employeeID;
this.name = name;
this.gender = gender;
this.mySubjects.add(s);
}
public void addSubject(Subject s, boolean b){
if(mySubjects.size()<4)mySubjects.add(s);
else throw OutOfBoundsError;
}
public void removeSubject(Subject s, boolean b){
mySubject.remove(s);
}
public void addSubject(Subject s){
s.changeTeacher(s);
}
public void removeSubject(Subject s){
mySubject.remove(s);
}
Add the following methods & fields to Student class
private Teacher teacher;
public Subject(int subjectID, String subjectName, double fee, Teacher t) {
this.subjectID = subjectID;
this.subjectName = subjectName;
this.fee = fee;
this.setTeacher(t);
}
public void setTeacher(Teacher t){
try{
t.addSubject(this);
teacher=t;
}
catch(OutOfBoundsError e){
System.out.println(t.getName()+" already has a full schedule.");
}
}
public void changeTeacher(Teacher t){
teacher.removeSubject(this);
teacher = t;
t.addSubject(this);
}
Question 2)
make a new double field, constructor parameter (for every constructor in the class), mutator method and accessor mutator called maxHour in the class Subject
add a double field to the teacher class called salary. If the teacher is part-time, set this to 0 in the constructor.
add this method to Teacher class:
public double getSalary(){
if(salary!=0) return salary;
double s=0;
for(Subject i: mySubjects) s+=i.getFee()*i.getMaxHours();
return s;
}
You honestly no longer need the PartTimeSalary class now.
Question 3
make a new Address field, constructor parameter (for every constructor in the class), mutator method and accessor mutator called myAddress in the class Teacher
Don't bother with the ArrayList stuff in your Address Class

Error cannot find symbol, method getcustomerdiscount() [duplicate]

This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed 3 years ago.
Having an issue on line 192 in netbeans
cannot seem to figure out were the issue is
Line 192: System.out.println("Percent off: "+customer.getcustomerDiscount());
Error:
cannot find symbol
symbol: method getcustomerDiscount()
location: variable customer of type Customer
(PS yes i know it's in 1 java file, it's supposed to be)
package Driver2;
import java.util.Scanner;
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
class Person{
private String name;
private String address;
private String number;
private int customerPurchase;
//Constructors
public Person(String name, String address, String number, int customerPurchase){
this.name = name;
this.address = address;
this.number = number;
this.customerPurchase = customerPurchase;
}
public Person(){}
//Accessors
public String getName(){
return this.name;
}
public String getAddress(){
return this.address;
}
public String getNumber(){
return this.number;
}
public int getcustomerPurchase(){
return this.customerPurchase;
}
//Mutators
public void setName(String n){
this.name = n;
}
public void setAddress(String a){
this.address = a;
}
public void setNumber(String n){
this.number = n;
}
public void setcustomerPurchase(int a){
this.customerPurchase = a;
}
}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
class Customer extends Person{
private String customerNumber;
private boolean recieveMail;
//Constructors
public Customer(String name, String address, String number, String customerN, boolean rm, int customerPurchase) {
super(name, address, number, customerPurchase);
this.customerNumber = customerN;
this.recieveMail = rm;
}
public Customer(){}
//Accessors
public String getCustomerNumber(){
return this.customerNumber;
}
public boolean getRecieveMail(){
return this.recieveMail;
}
//Mutators
public void setCustomerNumber(String c){
this.customerNumber = c;
}
public void setRecieveMail(boolean r){
this.recieveMail = r;
}
}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
class Driver1 extends Customer
{
private int customerPurchase = 0;
private int customerDiscount;
//Constructors
/* public Driver1(String name, String address, String number, String customerN, boolean rm, int customerPurchase)
{
super();
this.customerPurchase = customerPurchase;
//this.customerDiscount = customerDiscount;
}*/
public Driver1(String name, String address, String number, String customerN, boolean rm, int customerPurchase) {
//super(name, address, number, customerPurchase, customerN, rm);
//this.customerPurchase = customerN;
//this.customerDiscount = pc;
}
public Driver1()
{}
//Accessors
//#Override
//public int getcustomerPurchase()
//{
// return this.customerPurchase;
//}
public int getcustomerDiscount()
{
return this.customerDiscount;
}
//Mutators
/*
#Override
public void setcustomerPurchase(int c)
{
this.customerPurchase = c;
}*/
public void setcustomerDiscount(int r)
{
this.customerPurchase = r;
if (r >= 500)
{
System.out.print("5%");
}
else if (r >= 1000)
{
System.out.print("6%");
}
else if (r >= 1500)
{
System.out.print("7%");
}
else if (r >= 2000)
{
System.out.print("10%");
}
else
{
System.out.print("");
}
}
}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
class Driver3
{
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
System.out.print("Enter name of customer:");
String name1 = scanner.nextLine();
System.out.print("Enter address of customer:");
String address1 = scanner.nextLine();
System.out.print("Enter phone number of customer:");
String number1 = scanner.nextLine();
System.out.print("Enter customer number:");
String customerNumber = scanner.nextLine();
System.out.print("Enter yes/no -- does the customer want to recieve mail?:");
String answer = scanner.nextLine();
boolean recieveMail = (answer.equals("yes"));
System.out.print("Enter amount customer has spent:");
int customerPurchase = scanner.nextInt();
Customer customer = new Customer(name1, address1, number1, customerNumber, recieveMail, customerPurchase);
System.out.println("\nCustomer: ");
System.out.println("Name: "+customer.getName());
System.out.println("Address: "+customer.getAddress());
System.out.println("Phone Number: "+customer.getNumber());
System.out.println("Customer Number: "+customer.getCustomerNumber());
System.out.println("Recieve Mail?: "+customer.getRecieveMail());
System.out.println("Amount Purchased: "+customer.getcustomerPurchase());
System.out.println("Percent off: "+customer.getcustomerDiscount());
}
}
Additional
I am a little confused, i called the driver 1 and even made an object and couldent get it to work also another question popped up when i tested the if else statement another way
Question Should i leave the if else statement inside the setter? or put into the getter? i think i have an issue were i am not retrieving a string because it is all set as a INT
You are trying to call getcustomerDiscount on a Customer object. The method is not defined on this class but on Driver1.
Also: You should try to use Java naming conventions, in this case getcustomerDiscount and setcustomerDiscount should be renamed to getCustomerDiscount and setCustomerDiscount respectively.

Find higest value among objects created in a class

Can anybody explain how I get the highest value from all the objects I have created in my main class?
In this example I have created 2 students objects in my main class and added some course names and grades.
I have made 2 static arrays to store the information from the different objects but it doesn't return the object with the highest grade.
How do I store the highest grade from the student objects created?
public class CMate {
private static String[] studentName = new String[2];
private static int[][] gradeAssigned = new int[2][3];
private static int higGrade = 0;
private String name;
private int cpr;
private String[] courseName = new String[3];
private int[] grade = new int[3];
private int numberOfCourse;
private int numberOfGrades;
private static int counter = 0;
CMate(String name, int cpr) {
// building constructor
System.out.println("Creating object nr " + counter);
this.name = name;
this.cpr = cpr;
// insert name into array
studentName[counter] = name;
for (int i = 0; i < numberOfCourse; i++) {
gradeAssigned[counter][i] = grade[i];
}
counter++;
}
public void addcourseName(String nameOfCourse) {
courseName[numberOfCourse] = nameOfCourse;
numberOfCourse++;
}
public void addGrade(int gradeNr) {
grade[numberOfGrades] = gradeNr;
numberOfGrades++;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCpr() {
return cpr;
}
public void setCpr(int cpr) {
this.cpr = cpr;
}
public String[] getCourseName() {
return courseName;
}
public void setCourseName(String[] courseName) {
this.courseName = courseName;
}
public int[] getGrade() {
return grade;
}
public void setGrade(int[] grade) {
this.grade = grade;
}
public String toString() {
String studentInfo = "";
System.out.println("------------------------------\n student " + name + " CPR " + cpr);
for (int i = 0; i < numberOfCourse; i++) {
studentInfo += " Course " + courseName[i] + "Grade " + grade[i];
}
return studentInfo;
}
public double averageGrade() {
double total = 0;
for (int i = 0; i < numberOfGrades; i++) {
total += grade[i];
}
return (total / numberOfGrades);
}
public void higestGrade() {
for (int i = 0; i < studentName.length; i++) {
if (grade[i] > higGrade) {
higGrade = grade[i];
}
}
}
public void higestObjectGrade() {
System.out.println(higGrade);
}
}
I don't fully understand your code, but here's a simplified version, including a static field to keep all students, and a static function to return the highest grade:
class Student {
public final static List<Student> allCreatedStudents = new ArrayList<Student>();
String name;
int[] grades = new int[3];
public Student(String name){
this.name = name;
allCreatedStudents.add(this); // Every time a student is created, he is recorded in the static list
}
public void setGrade(int grade, int index){
this.grades[index] = grade;
}
public static int getHighestGrade(){
int highestGrade = 0;
for(Student s : allCreatedStudents){ // Loop through all students
for(int i=0; i<s.grades.length; i++){ // Loop through all grades
if(s.grades[i]>highestGrade)
highestGrade = s.grades[i];
}
}
return highestGrade;
}
}

Java: how to return an Array?

this is the code, from what I understand, it is suppose to work.
Also when I debug my program, it seems that the array is being filled with the objects that the same method is creating.
But still, when I try to print it, it shows me "null" back agian, like the "return" does not work.
Why is it happening?
public class Course {
String courseName;
String teacherName;
int gradeAv;
static int counter;
static int maxNumOfStudents;
Student studentsArray[] = new Student[5];
int numOfStudents = studentsArray.length;
public Course() {
}
public Course(String courseName) {
this();
this.courseName = courseName;
}
public Course(String courseName, String teacherName) {
this(courseName);
this.courseName = courseName;
this.teacherName = teacherName;
}
public Student[] addStudent(String name, int age, int grade) {
for (int i = 0; i < 5; i++) {
studentsArray[i] = new Student(name, age, grade);
age += 10;
grade += 10;
}
return studentsArray;
}
public void printStudentArray(Student studentArray[]) {
studentArray = this.studentsArray;
for (int i = 0; i < studentsArray.length; i++) {
System.out.println(studentsArray[i]);
}
}
public int gradeAv() {
for (int i = 0; i < studentsArray.length; i++) {
int temp = 0;
if (studentsArray[i].grade > temp) {
gradeAv = temp;
System.out.println(gradeAv);
}
}
return gradeAv;
}
public void printCourse() {
System.out.println("Course: ");
System.out.println("Course Name: " + courseName + ". "
+ "Teacher's Name: " + teacherName + ". "
+ "Number Of Students: " + numOfStudents + ". ");
}
}
This is my main class:
public class MainClass {
public static void main(String[] args) {
Student stud = new Student();
Course cour = new Course("Java", "Ronni");
stud.addStudent("Joe", 23, 100);
stud.printStudent();
System.out.println();
stud.printCourse();
System.out.println();
cour.printStudentArray(cour.studentsArray);
System.out.println();
// cour.gradeAv();
}
}
in
Student stud = new Student();
Course cour = new Course("Java", "Ronni");
stud.addStudent("Joe", 23, 100);
stud.addStudent("Joe", 23, 100); will not add any students to your course. stud is an instance of a completely different class, Student, and the implementation of Student is not in the code you've posted.
call the addStudent method of cour instead of the one for stud
cour.addStudent("Joe", 23, 100);
instead
I would also like to add that there are a lot of curious elements to your code, some of which people have brought up in the comments. It would be tedious to list them all. I'd take a look-through, just to make sure you're not doing redundant things.
Try this for example:
Course class:
import java.util.ArrayList;
import java.util.List;
public class Course {
private List<Student> students = new ArrayList<Student>();
private String teacherName;
private String subjectName;
public Course(String subjectName, String teacherName) {
this.subjectName = subjectName;
this.teacherName = teacherName;
}
public void addStudent(Student student) {
students.add(student);
}
public float getAverageGrade() {
float grade = 0;
for (Student student : students) {
grade += student.getGrade();
}
return grade / students.size();
}
public void printCourse() {
System.out.println("Course "+subjectName+" taught by "+teacherName);
System.out.println("Students:");
printStudents();
System.out.println("Aberage grade: "+getAverageGrade());
}
public void printStudents() {
for (Student student : students) {
System.out.println(student.getName()+"\t age "+student.getAge()+" \t grade "+student.getGrade());
}
}
}
Student class:
public class Student {
private String name;
private int age;
private int grade;
public Student(String name, int age, int grade) {
this.grade = grade;
this.age = age;
this.grade = grade;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
}

Categories

Resources