I am having issues performing a System.out.print() that references an ArrayList in Main. My code...
import java.util.*;
public class Roster {
public static void main(String[]args){
ArrayList<Student> StudentArray = new ArrayList<Student>();
StudentArray.add(new Student("1","John","Smith","John1989#gmail.com", 20, 88, 79, 59));
StudentArray.add(new Student("2","Susan","Erickson","Erickson_1990#gmailcom", 19, 91, 72, 85));
StudentArray.add(new Student("3","Jack","Napoli","The_lawyer99yahoo.com", 19, 85, 84, 87));
StudentArray.add(new Student("4","Erin","Black","Erin.black#comcast.net", 22, 91, 98, 82));
StudentArray.add(new Student("5","Jack","Black","jblack14#wgu.edu", 65, 99, 98, 97));
//Example of printing specific student data using getters.
System.out.println("");
for (Student a: StudentArray) {
System.out.println(a.getStuID());
System.out.println(a.getFName());
System.out.println(a.getLName());}
}
}
public static void print_all(){
System.out.println("");
for (Student s: StudentArray) {
System.out.printf("%s\n",s);
}
}
//Print All Student Info
}
Student Class
public class Student {
private String StuID;
private String FName;
private String LName;
private String Email;
private int Age;
private double Grade1;
private double Grade2;
private double Grade3;
public Student (String stuid, String fname, String lname, String email,
int age, double grade1, double grade2, double grade3)
{
this.StuID = stuid;
this.FName =fname;
this.LName = lname;
this.Email = email;
this.Age = age;
this.Grade1 = grade1;
this.Grade2 = grade2;
this.Grade3 = grade3;
}
public String getStuID(){
return this.StuID;
}
public String getFName(){
return this.FName;
}
public String getLName(){
return this.LName;
}
public String getEmail(){
return this.Email;
}
public int getAge(){
return this.Age;
}
public double getGrade1(){
return this.Grade1;
}
public double getGrade2(){
return this.Grade2;
}
public double getGrade3(){
return this.Grade3;
}
public String setStuID(String newStuID){
return (this.StuID= newStuID);
}
public String setFName(String newFName){
return (this.FName= newFName);
}
public String setLName(String newLName){
return (this.LName= newLName);
}
public String setEmail(String newEmail){
return (this.Email= newEmail);
}
public int setAge(int newAge){
return (this.Age= newAge);
}
public double setGrade1(double newGrade1){
return (this.Grade1= newGrade1);
}
public double setGrade2(double newGrade2){
return (this.Grade2= newGrade2);
}
public double setGrade3(double newGrade3){
return (this.Grade1= newGrade3);
}
public String toString() {
return String.format("StuID: %s\t First Name: %s\t Last Name: %s\t E-Mail: %s\t Age: %s\t Grade1: %s\t Grade2: %s\t Grade3: %s\t", this.StuID, this.FName, this.LName, this.Email,
this.Age, this.Grade1, this.Grade2, this.Grade3);
}
}
I know this is probably an easy task for some (or most), but I have been struggling on this for the past few days. If I move the "print_all" into the Main (like the "Example") method, it works just fine. But the exercise calls for a new method referencing the Main. If you could help I would be sincerely grateful. My college's material is horrible at explaining this. Thank you.
Maybe you want to do something like this:
import java.util.ArrayList;
public class Roster {
ArrayList<Student> studentArray;
public Roster(ArrayList<Student> ar)
{
studentArray=ar;
}
public void print_all(){
System.out.println("");{
for (Student s: studentArray) {
System.out.printf("%s\n",s);}}
//Print All Student Info
}
public static void main(String[]args){
ArrayList<Student> studentArray = new ArrayList<Student>();
studentArray.add(new Student("1","John","Smith","John1989#gmail.com", 20, 88, 79, 59));
studentArray.add(new Student("2","Susan","Erickson","Erickson_1990#gmailcom", 19, 91, 72, 85));
studentArray.add(new Student("3","Jack","Napoli","The_lawyer99yahoo.com", 19, 85, 84, 87));
studentArray.add(new Student("4","Erin","Black","Erin.black#comcast.net", 22, 91, 98, 82));
studentArray.add(new Student("5","Jack","Black","jblack14#wgu.edu", 65, 99, 98, 97));
//Example of printing specific student data using getters.
Roster r=new Roster(studentArray);
r.print_all();
}
}
As you can see the method print_all is now a method of the class Roster and you can pass the reference of the array initialized in the main in the constructor.
Related
I have an issue at TestVolleyTeam.java. I cannot get the list arrays to work, I am honestly confused. I don't really know how to assign the lists with the "for" loop, I have probably made a mistake there.
The code is supposed to show the list of the players by using both the VolleyPlayer class and the VolleyTeam class through the TestVolleyTeam class. Can anyone spot the mistakes I've made?
class VolleyPlayer {
private String name;
private String surname;
private int flnum;
private int height;
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public int getFlnum() {
return flnum;
}
public int getHeight() {
return height;
}
public VolleyPlayer(String n, String sur, int fl, int h) {
name = n;
surname = sur;
flnum = fl;
height = h;
}
public VolleyPlayer(String n, String sur, int fl) {
this(n, sur, fl, 185);
}
public VolleyPlayer(String n, String sur) {
this(n, sur, 3);
}
public VolleyPlayer(String n) {
this(n, "Brown");
}
}
import java.util.ArrayList;
public class VolleyTeam {
private String teamname;
private String city;
private int year;
private ArrayList<VolleyPlayer> players;
public String getTeamname() {
return teamname;
}
public String getCity() {
return city;
}
public int getYear() {
return year;
}
public ArrayList<VolleyPlayer> getPlayers() {
return players;
}
public void setTeamname(String newTeamname) {
this.teamname = teamname;
}
public void setCity(String newCity) {
this.city = city;
}
public void setYear(int newYear) {
this.year = year;
}
public void setPlayers(ArrayList<VolleyPlayer> newPlayers) {
this.players = players;
}
}
import javax.swing.JOptionPane;
import java.util.Scanner;
import java.util.ArrayList;
public class TestVolleyTeam {
public static void main(String[] args) {
VolleyTeam myObj = new VolleyTeam();
String teamname = JOptionPane.showInputDialog(null, "What is the name of the team?", "Input");
myObj.setTeamname(teamname);
String city = JOptionPane.showInputDialog(null, "What is the city of the team?", "Input");
myObj.setCity(city);
String input = JOptionPane.showInputDialog(null, "What is the foundation year of the team?",
"Input");
int year = Integer.parseInt(input);
myObj.setYear(year);
myObj.getTeamname();
myObj.getCity();
myObj.getYear();
VolleyPlayer first = new VolleyPlayer("Michael", "Scott", 1, 175);
VolleyPlayer second = new VolleyPlayer("Jim", "Halpert", 2, 191);
VolleyPlayer third = new VolleyPlayer("Dwight", "Schrute", 3, 189);
VolleyPlayer fourth = new VolleyPlayer("Darryl", "Philbin", 4, 188);
VolleyPlayer fifth = new VolleyPlayer("Andy", "Bernard", 5, 182);
VolleyPlayer sixth = new VolleyPlayer("Oscar", "Martinez", 6, 173);
VolleyPlayer seventh = new VolleyPlayer("Stanley", "Hudson", 7, 180);
VolleyPlayer eighth = new VolleyPlayer("Kevin", "Malone", 8, 185);
VolleyPlayer ninth = new VolleyPlayer("Creed", "Bratton", 9, 183);
VolleyPlayer tenth = new VolleyPlayer("Toby", "Flederson", 10, 177);
ArrayList<VolleyPlayer> vplist = new ArrayList<VolleyPlayer>();
for (VolleyPlayer volleyPlayer : vplist) {
vplist.add(volleyPlayer);
}
myObj.getPlayers();
myObj.setPlayers(vplist);
ArrayList<VolleyPlayer> vplist2 = volleyTeam.getPlayers();
for (VolleyPlayer volleyPlayer : vplist2) {
vplist2.add(volleyPlayer);
}
volleyTeam.getPlayers();
volleyTeam.setPlayers(vplist2);
JOptionPane.showMessageDialog(null, vplist2, teamname + " " + city + ", " + year,
JOptionPane.INFORMATION_MESSAGE);
}
}
The List is empty when you start, this code
for (VolleyPlayer volleyPlayer : vplist) {
is attempted to loop over an empty List. I think I see what you want, and it can be achieved with something like
List<VolleyPlayer> vplist = new ArrayList<>(Arrays.asList(
first, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth));
Then you don't need a loop to add first - tenth to your vplist. Note I changed it the diamond operator <> on construction. And used Arrays.asList to add the elements.
Since you must use a for loop, create an inline array. Like,
for (VolleyPlayer volleyPlayer : new VolleyPlayer[] {
first, second, third, fourth, fifth, sixth, seventh,
eighth, ninth, tenth }) {
So I have a relatively simple program using two classes. When I compile the class I want to run I get an error saying cannot find symbol "Fighter" which is the name of my class that I am using the objects from. Both classes are in the same package. NOTE It works fine in NetBeans but I prefer to use VSC.
Here is my code.
Class I am running:
package project;
import java.util.ArrayList;
import java.util.Scanner;
public class Division
{
public static Scanner scanner = new Scanner(System.in);
public static void main(String args[])
{
ArrayList<Fighter> fighters = new ArrayList();
fighters.add(new Fighter("Conor McGregor", 29, "Ireland", 21, 3));
fighters.add(new Fighter("Gunnar Nelson", 28, "Iceland", 16, 3));
fighters.add(new Fighter("Stipe Miocic", 33, "USA", 17, 2));
fighters.add(new Fighter("Cody Garbrandt", 26, "USA", 11, 0));
fighters.add(new Fighter("Demetrious Johnson", 30, "USA", 27, 2));
fighters.add(new Fighter("Jose Aldo", 31, "Brazil", 26, 3));
fighters.add(new Fighter("George St Pierre", 40, "Canada", 25, 2));
fighters.add(new Fighter("Fabricio Werdum", 40, "Brazil", 22, 7));
fighters.add(new Fighter("Michael Bisping", 39, "United Kingdom", 30, 7));
displayAllFighters(fighters);
}
//Adds fighter to ArrayList
public static void addFighter(ArrayList<Fighter> fighters)
{
System.out.print("Please enter fighters name: \t");
String name = scanner.nextLine();
System.out.print("\nPlease enter fighters age: \t");
int age = scanner.nextInt();
scanner.nextLine();
System.out.print("\nPlease enter fighters country: \t");
String country = scanner.nextLine();
System.out.print("\nPlease enter amount of wins: \t");
int wins = scanner.nextInt();
System.out.print("\nPlease enter amount of losses: \t");
int losses = scanner.nextInt();
fighters.add(new Fighter(name, age, country, wins, losses));
System.out.println("Fighter Added!");
}
//Removes a fighter from ArrayList
public static void removeFighter(ArrayList<Fighter> fighters)
{
System.out.print("Please enter the name of the fighter you wish to remove: \t");
String name = scanner.nextLine();
for (Fighter fighter : fighters)
{
if (fighter.getName() == name)
{
fighters.remove(fighter);
}
}
}
public static void displayAllFighters(ArrayList<Fighter> fighters)
{
for (Fighter fighter : fighters)
{
System.out.println(fighter);
System.out.println("==========================================");
}
}
public static int countWinPercentLowerThan(ArrayList<Fighter> fighters , int value)
{
int count = 0;
for (Fighter fighter : fighters)
{
if (fighter.getPercent() < value)
{
count++;
}
}
return count;
}
public static int countWinPercentGreaterThan(ArrayList<Fighter> fighters , int value)
{
int count = 0;
for (Fighter fighter : fighters)
{
if (fighter.getPercent() > value)
{
count++;
}
}
return count;
}
}
Class that isn't being recognized.
package project;
public class Fighter
{
private String name;
private int age;
private String country;
private int wins;
private int losses;
public Fighter(String name, int age, String country, int wins, int losses)
{
this.name = name;
this.age = age;
this.country = country;
this.wins = wins;
this.losses = losses;
}
public Fighter(String name)
{
this.name = name;
this.age = 0;
this.country = "TBA";
this.wins = 0;
this.losses = 0;
}
public String getName()
{
return this.name;
}
public void setName(String name)
{
this.name = name;
}
public int getAge()
{
return this.age;
}
public void setAge(int age)
{
this.age = age;
}
public String getCountry()
{
return this.country;
}
public void setCountry(String country)
{
this.country = country;
}
public int getWins()
{
return this.wins;
}
public void setWins(int wins)
{
this.wins = wins;
}
public int getLosses()
{
return this.losses;
}
public void setLosses(int losses)
{
this.losses = losses;
}
public String toString()
{
return "Fighter Name: " + this.name + ".\nFighter age: " + this.age + ".\nFighter nation: " + this.country + ".\nFighter wins: " + this.wins + ".\nFighter losses: " + this.losses + ".";
}
public void updateWin()
{
this.wins++;
}
public void updateLosses()
{
this.losses++;
}
public double getPercent()
{
int totalFights = this.wins + this.losses;
double percent = this.wins * 100/totalFights;
return percent;
}
}
Thank you in advanced!
I have created a program that contains an ArrayList with separated "double" values for student grades. However, the course calls for creating an int Array of grades, instead of the separate values I had previously.
My code for Student Class (I have deleted irrelevant code to cut to the chase):
public class Student {
private int[] Grades = new int[3];
public Student(String stuid, String fname, String lname, String email, int age, int[] grades) {
this.Grades = grades;
}
public int[] getGrades() {
return Grades;
}
public void setGrades(int[] grades) {
Grades = grades;
}
public String toString() {
return String.format("StuID: %s\t First Name: %s\t Last Name: %s\t E-Mail: %s\t Age: %s\t Grades: %s\t",
this.StuID, this.FName, this.LName, this.Email, this.Age, this.Grades);
}
}
Roster Class:
import java.util.ArrayList;
public class Roster {
static ArrayList<Student> studentArray;
public Roster(ArrayList<Student> ar) {
studentArray = ar;
}
// 3.C - Print Average Grade
public static void print_average_grade(String studentID) {
for (Student v : studentArray) {
if (v.getStuID().equals(studentID)) {
double total = v.getGrade1() + v.getGrade2() + v.getGrade3();
double average = total / 3;
System.out.println("Student ID#" + studentID + " Grade AVG= " + average);
}
}
}
public static void main(String[] args) {
ArrayList<Student> studentArray = new ArrayList<Student>();
studentArray.add(new Student("1", "John", "Smith", "John1989#gmail.com", 20, 88, 79, 59));
studentArray.add(new Student("2", "Susan", "Erickson", "Erickson_1990#gmailcom", 19, 91, 72, 85));
studentArray.add(new Student("3", "Jack", "Napoli", "The_lawyer99yahoo.com", 19, 85, 84, 87));
studentArray.add(new Student("4", "Erin", "Black", "Erin.black#comcast.net", 22, 91, 98, 82));
studentArray.add(new Student("5", "Captain", "Planet", "PowIsYours#planet.edu", 65, 99, 98, 97));
new Roster(studentArray);
for (Student v : studentArray) {
print_average_grade(v.getStuID());
}
}
}
I have changed the separated values (Grade1, Grade2, Grade3) into an "int[] Grades" array and modified the constructor and have added the setter and the getter. So, I think the Student class is good to go, however the Roster class, is where I am stuck. Two things:
1) How do I add values of the Grades into the Array that is now a part of the ArrayList?
2) How would I adjust my AVG Grade method to perform the same task as before but with the values of the Array?
Any help would be great because I have been stuck on this for days.
Thanks.
P.S. If posting the full code would be easier, I will gladly post it for any aid on this problem.
I tried to fix your code according to the two requirements (array, AVG). Please see the following codes (I have tested it).
Student Class:
public class Student {
String StuID;
String FName;
String LName;
String Email;
int Age;
private int[] Grades = new int[3];
public Student(String stuid, String fname, String lname, String email, int age, int[] grades) {
this.StuID = stuid;
this.FName = fname;
this.LName = lname;
this.Email = email;
this.Grades = grades;
}
public int[] getGrades() {
return Grades;
}
public void setGrades(int[] grades) {
Grades = grades;
}
public String toString() {
return String.format("StuID: %s\t First Name: %s\t Last Name: %s\t E-Mail: %s\t Age: %s\t Grades: %s\t", this.StuID, this.FName, this.LName, this.Email, this.Age, this.Grades);
}
public String getFName() {
return FName;
}
public void setFName(String fName) {
FName = fName;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public int getAge() {
return Age;
}
public void setAge(int age) {
Age = age;
}
public String getStuID() {
return StuID;
}
public void setStuID(String stuID) {
StuID = stuID;
}
public String getLName() {
return LName;
}
public void setLName(String lName) {
LName = lName;
}
}
Roster Class:
import java.util.ArrayList;
public class Roster {
ArrayList<Student> studentArray;
public Roster(ArrayList<Student> ar) {
studentArray = ar;
}
// 3.C - Print Average Grade
public void print_average_grade(String studentID) {
for (Student v : studentArray) {
if (v.getStuID().equals(studentID)) {
double total = v.getGrades()[0] + v.getGrades()[1] + v.getGrades()[2];
double average = total / 3;
System.out.println("Student ID#" + studentID + " Grade AVG= " + average);
}
}
}
public static void main(String[] args) {
ArrayList<Student> studentArray = new ArrayList<Student>();
int[] grades1 = {88, 79, 59};
int[] grades2 = {91, 72, 85};
int[] grades3 = {85, 84, 87};
int[] grades4 = {91, 98, 82};
int[] grades5 = {99, 98, 97};
studentArray.add(new Student("1", "John", "Smith", "John1989#gmail.com", 20, grades1));
studentArray.add(new Student("2", "Susan", "Erickson", "Erickson_1990#gmailcom", 19, grades2));
studentArray.add(new Student("3", "Jack", "Napoli", "The_lawyer99yahoo.com", 19, grades3));
studentArray.add(new Student("4", "Erin", "Black", "Erin.black#comcast.net", 22, grades4));
studentArray.add(new Student("5", "Captain", "Planet", "PowIsYours#planet.edu", 65, grades5));
Roster r = new Roster(studentArray);
for (Student v : studentArray) {
r.print_average_grade(v.getStuID());
}
}
}
Output:
Student ID#1 Grade AVG= 75.33333333333333
Student ID#2 Grade AVG= 82.66666666666667
Student ID#3 Grade AVG= 85.33333333333333
Student ID#4 Grade AVG= 90.33333333333333
Student ID#5 Grade AVG= 98.0
Here's how I did the same project. Mine is still being graded, so I have no idea if it will pass the first time or not. But maybe it will help someone by my sharing it.
import java.util.ArrayList;
public class Roster {
public static ArrayList<Student> students = new ArrayList<>();
public static void main(String[] args)
{
// input student grades
int[] grade0 = {0,0,0}; // filler to make grade array equal to student ID
int[] grade1 = {88, 79, 59};
int[] grade2 = {91, 72, 85};
int[] grade3 = {85, 84, 87};
int[] grade4 = {91, 98, 82};
int[] grade5 = {99, 98, 97};
// input student info
addStudent(0, "null", "null", "null#null.com", 0, grade0); // filler to align student ID with array number
addStudent(1, "John", "Smith", "John1989#gmail.com", 20, grade1);
addStudent(2, "Suzan", "Erickson", "Erickson_1990#gmailcom", 19, grade2);
addStudent(3, "Jack", "Napoli", "The_lawyer99yahoo.com", 19, grade3);
addStudent(4, "Erin", "Black", "Erin.black#comcast.net", 22, grade4);
addStudent(5, "Habib", "Trump", "someemail#mywqu.edu", 42, grade5);
// printing related subroutines/methods
Student student = students.get(3); //get student 3 for printing
System.out.println("Print one student:");
student.print(); //prints specific student data as per 2.D
printAllStudents(); //print all students as per 3.B
print_invalid_emails(); //checks email addresses for proper form as per 3.D
printAverageGrade(); //print grades as per 3.C
remove(); // removes student 5 as per 3.A
printAllStudents(); // shows student 3 has been removed
remove(); // shows error as student already removed
}
public static void addStudent(int studentID, String firstName, String lastName, String email, int age, int[] grades){
Student newStudent = new Student(studentID, firstName, lastName, email, age, grades);
students.add(newStudent);
}
public static void remove(){ // remove student
try{
System.out.println("Remove student: 5 ");
students.remove(5);
} catch (IndexOutOfBoundsException e) {
System.err.println("IndexOutOfBoundsException: No such student ID");
}}
public static void printAverageGrade(){ // print Average Grade
System.out.println("Print Average Grade: ");
for(Student eachItem : students){
double total = eachItem.getgrades()[0] + eachItem.getgrades()[1] + eachItem.getgrades()[2];
double average = total / 3;
System.out.println(average);
}}
public static void printAllStudents(){ // print All Students
System.out.println("Print all Students: ");
for(int i=0; i < students.size(); i++){
students.get(i).print();
}}
public static void print_invalid_emails(){ // check Email Addresses for proper form
System.out.println("Check for proper form of email addresses: ");
for(Student student : students) {
if (student.getemail().contains("#") && student.getemail().contains(".") && !student.getemail().contains(" ")){
System.out.println("Passed format check");
}
else
{
System.out.println("Invalid email address");
}}
}}
public class Student extends Roster
{
private int studentID;
private String firstName;
private String lastName;
private String email;
private int age;
private int[] grades = new int[3];
public Student(int studentID, String firstName, String lastName, String email, int age, int[] grades)
{
setstudentID(studentID);
setfirstName(firstName);
setlastName(lastName);
setemail(email);
setage(age);
setgrades(grades);
}
public int getstudentID(){
return studentID;
}
public void setstudentID(int studentID)
{
this.studentID = studentID;
}
public String getfirstName(){
return firstName;
}
public void setfirstName(String firstName)
{
this.firstName = firstName;
}
public String getlastName(){
return lastName;
}
public void setlastName (String lastName)
{
this.lastName = lastName;
}
public String getemail(){
return email;
}
public void setemail(String email)
{
this.email = email;
}
public int getage(){
return age;
}
public void setage(int age)
{
this.age = age;
}
public void setgrades(int[] grades){
this.grades = grades;
}
public int[] getgrades(){
return grades;
}
public void print(){
System.out.println(
"Student ID = \t" + getstudentID() + ", \t" +
"First Name = \t" + getfirstName() + ", \t" +
"Last Name = \t" + getlastName() + ", \t" +
"Email = \t" + getemail() + ", \t" +
"Age = \t" + getage());
}
}
This is the complete code . And I need to write a Test case. Please help me out writing the Test Case, i am a beginner and very new to Junit.
public class Register1 {
String name;
String location;
int id;
int salary;
public Register1(String name, String location, int id, int salary) {
this.name = name;
this.location = location;
this.id = id;
this.salary = salary;
}
}
import java.util.*;
public class Employee {
public static void main(String[] args) {
ArrayList<Register1> Emp = new ArrayList<Register1>();
Emp.add(new Register1("Jack", "London", 101, 800));
Emp.add(new Register1("Mike", "UK", 100, 60000));
Emp.add(new Register1("Andrew", "China", 103, 2000));
Emp.add(new Register1("Michel", "Korea", 106, 300000));
Emp.add(new Register1("Donald", "London", 102, 90000));
List<Register1> reg = new ArrayList<Register1>();
String input = "London";
for (Register1 adrs : Emp) {
if (adrs.location.equals(input)) {
reg.add(adrs);
}
}
for (Register1 adrs : reg) {
System.out.println("Employee from London:" + adrs.salary + " "
+ adrs.location + " " + adrs.id + " " + adrs.name);
}
}
}
OUTPUT:
Employee from London:800 London 101 Jack
Employee from London:90000 London 102 Donald
First, I'd extract the "logic" part of your program to a separate method:
public static List<Register1> filtrerByLocation (List<Register1> emp, String location) {
List<Register1> reg = new ArrayList<Register1>();
// A for loop would be nicer, IMHO, but keeping OP's style
Iterator<Register1> itr = emp.iterator();
while (itr.hasNext()) {
Register1 res = (Register1) itr.next();
if (res.location.equals("London")) {
reg.add(res);
}
}
}
Now, you could easily write a test suite for it. To take the example in the given main:
#Test
public void testFiler() {
List<Register1> emp = new ArrayList<Register1>();
emp.add(new Register1("Jack", "London", 101, 800));
emp.add(new Register1("Mike", "UK", 100, 60000));
emp.add(new Register1("Andrew", "China", 103, 2000));
emp.add(new Register1("Michel", "Korea", 106, 300000));
emp.add(new Register1("Donald", "London", 102, 90000));
List<Register1> res = filterByLocation(emp, "London");
assertEquals (2, res.size());
assertEquals ("Jack", res.get(0).getName());
assertEquals ("Donald", res.get(1).getName());
}
Here is an assignment I am having trouble with. I am still a newbie at Java. I can't seem to load the Students name and their grades. The names and grades should be hardcoded into main, doesn't have to be 25. So I did 4. I am having difficulty loading the data.
(Grades) Create a blueprint named Student that has two fields, a String for their name and a one-dimensional array of integers which are their grades (different students may have different number of grades). Finish the blueprint with a minimum of two constructors, a toString, and getters and setters. You can add more methods as you see fit.
Write a driver program that has, at a minimum, the following structure:
public static void main(String[] args) {
// we do not know the number of students but there will not be >25
Student[] students = new Student[25];
int numStudents = loadStudents(students);
printStudents(students,numStudents);
}
public static int loadStudents(Student[] s) { }
public static void printStudents(Student[] s, int numStudents) {}
}
Here is what I have so far.
student class:
public class Student {
String name;
int[] grades;
public Student()
{
}
public Student(String n,int[] g)
{
name=n;
grades=g;
}
public String toString(){
return "";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int[] getGrades() {
return grades;
}
public void setGrades(int[] grades) {
this.grades = grades;
}
}
driverclass:
public class Driver {
public static void main(String[] args) {
// we do not know the number of students but there will not be >25
Student[] students = new Student[25];
Student s1= new Student("John", new int[]{98, 92, 81});
Student s2= new Student("Claire", new int[]{75, 84, 91, 39});
Student s3= new Student("Steven", new int[]{88, 94, 65, 91,95});
Student s4= new Student("Jason", new int[]{97, 89, 85, 82});
int numStudents = loadStudents(students);
printStudents(students,numStudents);
}
public static int loadStudents(Student[] s) {
for(int i=0;i<4;i++){
s[i]=new Student();
System.out.println(s[i]);
}
}
public static void printStudents(Student[] s, int numStudents) {
if(numStudents < s.length){
System.out.println(s[numStudents]);
printStudents(s,numStudents-1);
}
}
}
There are some elegant solution also available for your problem,however if you want to modify your existing code do as per below in Driver class,
public class Driver {
public static void main(String[] args) {
Student[] students = new Student[25];
Student s1 = new Student("John", new int[] { 98, 92, 81 });
Student s2 = new Student("Claire", new int[] { 75, 84, 91, 39 });
Student s3 = new Student("Steven", new int[] { 88, 94, 65, 91, 95 });
Student s4 = new Student("Jason", new int[] { 97, 89, 85, 82 });
List<Student> stuList = new ArrayList<Student>();
stuList.add(s1);
stuList.add(s2);
stuList.add(s3);
stuList.add(s4);
int numStudents = loadStudents(students, stuList);
printStudents(students, numStudents);
}
public static int loadStudents(Student[] s, List<Student> list) {
int size = list.size();
for (int i = 0; i < list.size(); i++) {
s[i] = list.get(i);
System.out.println(s[i]);
}
return size;
}
public static void printStudents(Student[] s, int numStudents) {
if (numStudents == 0) {
return;
}
if (numStudents < s.length) {
System.out.println(s[numStudents]);
printStudents(s, numStudents - 1);
}
}
}
and modify the toString method in Student class.
public String toString(){
String str = "name : "+name;
for(int i=0;i<grades.length;i++){
str += grades[i] + " ";
}
return str;
}
I hope it should solve your problem.
First of all, you have to return an int from your loadStudents function. Second, you have four Student variables declared in your main function which cannot be accessed right now in the loadStudents function. A quick solution would be to pass them as parameters and use a different constructor in the loadStudents function.
There are, of course, more elegant ways to do it, just consider this answer as a bit of help for your assignment :)