Converting separate "double" values into an Array within an ArrayList - java

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());
}
}

Related

Using an arrayList to create a menu and using a text file as input(bufferedReader)

As you can see below I tried creating a switch case for choices
1. Name
2. Course then Name
3. Year Level then Name
4. Course then Year Level and the Name
5. Exit
I don't know how to use switch case so that I could sort everything according to the menu. I will be using comparable and I am only allowed to edit the method called compareTo. My mind is blank and I got no idea where to start.
20192215
Ang
Bryan
m
BSCS
4
20192200
Santos
Charlie
m
BSIT
2
20192452
Chua
Leah
f
BSIS
4
20190012
Yee
John
m
BSCS
2
These are the inputs from text file
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Scanner;
import java.util.Vector;
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
try {
BufferedReader br = new BufferedReader(new FileReader("c://student.txt"));
char g;
int yl, I;
String ln, fn, id, cors, con;
Student v[] = new Student[4];
Scanner sc= new Scanner(System.in);
boolean en = true;
boolean ent = true;
for(i = 0; i < 4; i++){
id = br.readLine();
ln = br.readLine();
fn = br.readLine();
g = br.readLine().charAt(0);
cors = br.readLine();
yl = Integer.parseInt(br.readLine());
v[i] = new Student(ln, fn, id, cors, g, yl);
}
while(en == true){
System.out.println("--------------------------------------");
System.out.println("--------------------------------------");
System.out.println("1. Name");
System.out.println("2. Course then Name");
System.out.println("3. Year Level then Name");
System.out.println("4. Course then Year Level and the Name");
System.out.println("5. Exit");
System.out.println("--------------------------------------");
System.out.println("--------------------------------------");
System.out.println("Choose Menu: ");
int choice = sc.nextInt();
switch(choice){
case 1 :
Arrays.sort(v);
display_array(v);
break;
case 2 :
Arrays.sort(v);
display_array(v);
break;
case 3 :
Arrays.sort(v);
display_array(v);
break;
case 4 :
Arrays.sort(v);
display_array(v);
break;
case 5 :
en = false;
System.out.println("\n\n \nTHANK YOU FOR USING THE PROGRAM!!");
break;
}
if(en != false){
System.out.println("Press [Enter key] to continue");
try{
System.in.read();
}catch(Exception e){
e.printStackTrace();
}
}
}
} catch (FileNotFoundException e) {
System.err.println("File not found");
} catch (IOException e) {
System.err.println("Unable to read the file.");
}
}
public static void display_array(Student arr_v[]) throws IOException{
System.out.println("--------------------------------------");
for(int i = 0; i < arr_v.length; i++){
arr_v[i].display();
}
System.out.println("--------------------------------------");
}
}```
```
public class Student implements Comparable {
private String lastname, firstname, studentid, course;
private char gender;
private int yearlevel;
public Student(String ln, String fn, String id, String cors, char g, int yl) {
lastname = ln;
firstname = fn;
studentid = id;
course = cors;
gender = g;
yearlevel = yl;
}
public int compareTo(Object anotherObject) {
Student anotherStudent = (Student) anotherObject;
int compareResult =
this.course.compareTo(anotherStudent.lastname);
if(compare )
return 0;
}
public void display() {
System.out.printf("ID: %-8s Name: %-20s Sex: %c Course: %-8s Year: %d\n", studentid, (lastname + ", " + firstname), gender, course, yearlevel );
}
public void setGender(char gender){
this.gender = gender;
}
public char getGender(){
return gender;
}
public void setLastname(String lastname){
this.lastname = lastname;
}
public String getLastname(){
return lastname;
}
public void setFirstname(String firstname){
this.firstname = firstname;
}
public String getFirstname() {
return firstname;
}
public void setStudentId(String studentid){
this.studentid = studentid;
}
public String getStudentId(){
return studentid;
}
public void setCourse(String course){
this.course = course;
}
public String getCourse(){
return course;
}
public void setYearLevel(int yearlevel){
this.yearlevel = yearlevel;
}
public int getYearLevel(){
return yearlevel;
}
}```
public final class Student {
private final String id;
private final String firstName;
private final String lastName;
private final char gender;
private final String course;
private final int yearLevel;
public Student(String id, String firstName, String lastName, char gender, String course, int yearLevel) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.gender = Character.toUpperCase(gender);
this.course = course;
this.yearLevel = yearLevel;
}
public void display(PrintStream out) {
out.format("Name : %s, %s\n", lastName, firstName);
out.format("Student ID : %s\n", id);
out.format("Course : %s\n", course);
out.format("Gender : %s\n", gender);
out.format("Year Level : %d\n", yearLevel);
}
}
public static void main(String... args) throws FileNotFoundException {
File file = new File("c://student.txt");
List<Student> students = readStudents(file);
display(students);
}
private static List<Student> readStudents(File file) throws FileNotFoundException {
try (Scanner scan = new Scanner(file)) {
List<Student> students = new ArrayList<>();
while (scan.hasNext()) {
String id = scan.next();
String lastName = scan.next();
String firstName = scan.next();
char gender = scan.next().charAt(0);
String course = scan.next();
int yearLevel = scan.nextInt();
students.add(new Student(id, firstName, lastName, gender, course, yearLevel));
}
return students;
}
}
private static void display(List<Student> students) {
System.out.println("--------------------------------------");
System.out.println("--------------------------------------");
System.out.println("1. Name");
System.out.println("2. Course then Name");
System.out.println("3. Year Level then Name");
System.out.println("4. Course then Year Level and the Name");
System.out.println("5. Exit");
System.out.println("--------------------------------------");
System.out.println("--------------------------------------");
students.forEach(student -> {
student.display(System.out);
System.out.println();
});
}
All programmers need to learn how to debug their code. If you are using an IDE then I recommend that you learn how to use its debugger.
You have some calls to method readLine() that you do not need. In the below code, I have marked these lines as comments. I also incorporated the methods display_array() and main() into class Student just so everything would be in the one class, but you don't have to do that.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Student {
private String lastname, firstname, studentid, course;
private char gender;
private int yearlevel;
public Student(String id, String ln, String fn, char g, String cors, int yl) {
studentid = id;
lastname = ln;
firstname = fn;
gender = g;
course = cors;
yearlevel = yl;
}
private static void display_array(Student[] v) {
for (Student s : v) {
s.display();
}
}
public void display() {
System.out.println("Name : " + lastname + ", " + firstname);
System.out.println("Student ID: " + studentid);
System.out.println("Course : " + course);
System.out.println("Gender : " + gender);
System.out.println("Year Level: " + yearlevel);
}
public void setGender(char gender){
this.gender = gender;
}
public char getGender(){
return gender;
}
public void setLastname(String lastname){
this.lastname = lastname;
}
public String getLastname(){
return lastname;
}
public void setFirstname(String firstname){
this.firstname = firstname;
}
public String getFirstname() {
return firstname;
}
public void setStudentId(String studentid){
this.studentid = studentid;
}
public String getStudentId(){
return studentid;
}
public void setCourse(String course){
this.course = course;
}
public String getCourse(){
return course;
}
public void setYearLevel(int yearlevel){
this.yearlevel = yearlevel;
}
public int getYearLevel(){
return yearlevel;
}
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("c:\\student.txt"));) {
char g;
int yl;
int i;
String ln;
String fn;
String id;
String cors;
Student v[] = new Student[Integer.parseInt(br.readLine())];
// br.readLine();
for (i = 0; i < v.length; i++) {
id = br.readLine();
ln = br.readLine();
fn = br.readLine();
// g = (char) br.read();
g = br.readLine().charAt(0);
cors = br.readLine();
yl = Integer.parseInt(br.readLine());
// if ((br.readLine()) != null)
// br.readLine();
v[i] = new Student(id, ln, fn, g, cors, yl);
}
display_array(v);
}
catch (FileNotFoundException e) {
System.err.println("File not found");
}
catch (IOException e) {
System.err.println("Unable to read the file.");
}
}
}
I also changed file student.txt. According to your code, the first line of the file needs to be the number of students in the file. In the sample file in your question, there are four students.
4
20192215
Ang
Bryan
m
BSCS
4
20192200
Santos
Charlie
m
BSIT
2
20192452
Chua
Leah
f
BSIS
4
20190012
Yee
John
m
BSCS
2

Visual Studio Code Java: Cannot find symbol (class name)?

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!

Referencing ArrayList in Main

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.

How to search for an element in an array? and How to add variables with declared methods into an array list?

I have 2 major troubles (that I'm aware of) with this program. Firstly, I don't know how to get FinalGrade and LetterGrade into the array. Secondly, I don't know how to use last name and first name to search for a student in the array. Let me know if you find other problems with my program. Thanks
This is the 1st class
package student;
public class Person {
protected String FirstName, LastName;
//Constructor
public Person(String FirstName, String LastName) {
this.FirstName = FirstName;
this.LastName = LastName;
}
//Getters
public String getFirstName() {
return FirstName;
}
public String getLastName() {
return LastName;
}
//Setters
public void setFirstName(String FirstName) {
this.FirstName = FirstName;
}
public void setLastName(String LastName) {
this.LastName = LastName;
}
}
This is the 2nd class:
package student;
import java.util.ArrayList;
import java.util.Scanner;
public class Student extends Person{
private int HomeworkAve, QuizAve, ProjectAve, TestAve;
private double FinalGrade;
private String LetterGrade;
//Constructor for the averages
public Student(int HomeworkAve, int QuizAve, int ProjectAve, int TestAve, String FirstName, String LastName)
{
super(FirstName, LastName);
this.HomeworkAve = HomeworkAve;
this.QuizAve = QuizAve;
this.ProjectAve = ProjectAve;
this.TestAve = TestAve;
}
//Method to calculate final grade and letter grade
//Final grade calculation
public double CalcGrade (int HomeworkAve, int QuizAve, int ProjectAve, int TestAve)
{
FinalGrade = (double)(0.15*HomeworkAve + 0.05*QuizAve + 0.4 * ProjectAve + 0.4*TestAve);
return FinalGrade;
}
//Letter grade calculation
public String CalcGrade ( double FinalGrade)
{
if ( FinalGrade >= 90.00)
LetterGrade="A";
else if(FinalGrade >= 80.00)
LetterGrade="B";
else if(FinalGrade>=70.00)
LetterGrade="C";
else if(FinalGrade>=60.00)
LetterGrade="D";
else LetterGrade="F";
return LetterGrade;
}
public String getFullName (String FirstName,String LastName)
{
String str1 = FirstName;
String str2 = LastName;
String FullName = str1+","+str2;
return FullName;
}
public Student(int HomeworkAve, int QuizAve, int ProjectAve, int TestAve, double FinalGrade, String LetterGrade, String FirstName, String LastName) {
super(FirstName, LastName);
this.HomeworkAve = HomeworkAve;
this.QuizAve = QuizAve;
this.ProjectAve = ProjectAve;
this.TestAve = TestAve;
this.FinalGrade = FinalGrade;
this.LetterGrade = LetterGrade;
}
//Setters for this student class
public void setHomeworkAve(int HomeworkAve) {
this.HomeworkAve = HomeworkAve;
}
public void setQuizAve(int QuizAve) {
this.QuizAve = QuizAve;
}
public void setProjectAve(int ProjectAve) {
this.ProjectAve = ProjectAve;
}
public void setTestAve(int TestAve) {
this.TestAve = TestAve;
}
public void setFinalGrade(int FinalGrade) {
this.FinalGrade = FinalGrade;
}
public void setLetterGrade(String LetterGrade) {
this.LetterGrade = LetterGrade;
}
//Getters for this student class
public int getHomeworkAve() {
return HomeworkAve;
}
public int getQuizAve() {
return QuizAve;
}
public int getProjectAve() {
return ProjectAve;
}
public int getTestAve() {
return TestAve;
}
public double getFinalGrade() {
return FinalGrade;
}
public String getLetterGrade() {
return LetterGrade;
}
public void DisplayGrade (){
System.out.println(FirstName+" "+LastName+"/nFinal Grade: "+FinalGrade+"/nLetter Grade: "+ LetterGrade);
}
public static void main(String[] args){
Scanner oScan = new Scanner(System.in);
Scanner iScan = new Scanner(System.in);
boolean bContinue = true;
int iChoice;
ArrayList<Student> students = new ArrayList<>();
while (bContinue == true)
{
//The menu
System.out.println("1. New Class List");
System.out.println("2. Search for a Student");
System.out.println("3. Exit");
System.out.println("Choose an item");
iChoice = iScan.nextInt();
//The 1st case: when the user wants to enter the new list
if (iChoice == 1){
System.out.println("Enter the number of students");
int numberOfStudents = iScan.nextInt();
for(int iCount = 0;iCount < numberOfStudents;){
System.out.println("Enter the name for Student " + ++iCount);
System.out.println("Enter First Name");
String FirstName = oScan.nextLine();
System.out.println();
System.out.println("Enter Last Name");
String LastName = oScan.nextLine();
System.out.println();
System.out.println("Enter Homework Average");
int HomeworkAve = iScan.nextInt();
System.out.println();
System.out.println("Enter Quiz Average");
int QuizAve = iScan.nextInt();
System.out.println();
System.out.println("Enter Project Average");
int ProjectAve = iScan.nextInt();
System.out.println();
System.out.println("Enter Test Average");
int TestAve = iScan.nextInt();
System.out.println();
How to get FinalGrade and LetterGrade??
Student hobbit = new Student(HomeworkAve,QuizAve, ProjectAve,TestAve,FirstName, LastName);
students.add(hobbit);
}
}
//The 2nd case: when the user wants to search for a student
else if (iChoice == 2)
{
System.out.println("Enter First Name");
String FirstName = oScan.nextLine();
System.out.println();
System.out.println("Enter Last Name");
String LastName = oScan.nextLine();
System.out.println();
Here is my revised code to find the student but I don't know how to print the array after I found it
int i = 0;
for (Student student : students) {
if (FirstName != null & LastName != null);{
if (student.getFirstName().equals(FirstName) && student.getLastName().equals(LastName)) {
System.out.println(students.get(i)); //this doesn't work
break;
}
i++;
}
}
//The 3r case: when the user wants to exit
else if (iChoice == 3)
{
bContinue = false;
}
}
}
}
You have an ArrayList of type Student and you are doing indexOf on a variable of type String. You will have to traverse the entire ArrayList and then do a comparison to find out if the student name mathces. Sample code:
int i = 0;
for (Student student : students) {
// Add null checks if first/last name can be null
if (student.getFirstName().equals(firstName) && student.getLastName().equals(lastName)) {
System.out.println("Found student at " + i);
break;
}
i++;
}
FinalGrade and LetterGrade are variables in each object, I think you are mistaken about the concept of an Array/ArrayList. The ArrayList only holds each Student object, not the variable in each object. You can go through each student and get their finalGrade and letterGrade with the get* functions. Before doing this, you should make a call to CalcGrade methods so the grades are calculated.

My toString() is returning only one object times the number of the total object

Can someone help solving this. I want to print all the object once please
public class Student {
private static String firstName;
private static String lastName;
private static int studentId;
private static String major;
private static double balance;
public Student (String fName, String lName,int id,String mjr,double blce) {
firstName = new String(fName);
lastName = new String(lName);
studentId = id;
major = new String(mjr);
balance = blce;
}
public String toString () {
return firstName + "\t" + lastName + "\t" + studentId + "\t" + major + "\t$" + balance;
}
public boolean equals (Object obj) {
if (obj instanceof Student) {
Student collegeStud = (Student) obj;
return (this.firstName.equals(collegeStud.firstName));
} else
return false;
}
public static String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public static String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public static int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public static String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
public static double getBalance() {
return balance;
}
/*
* .commmm
*/
public void setBalance(double balance) {
this.balance = balance;
}
public static void main (String[] args) {
Student Mike = new Student ("Mike","Versace", 99, "CS",0.00);
Student John = new Student ("John","Sling" ,97, "Maths", 20.00);
Student Bob = new Student ("Bob","Tomson" ,57, "Physic",5.00);
System.out.println (Mike.toString() + "\n" + John.toString());
if (Mike.equals(John))
System.out.println ("Mike is John");
else
System.out.println ("Mike is NOT John");
}
}
import java.io.ObjectInputStream.GetField;
public class StudentList {
private int numberOfStudents=0;
private Student[] studentListArray;
//private int studentCount = 0;
StudentList () {
numberOfStudents=0;
studentListArray = new Student[100];
}
public void createStudent(String firstName, String lastName,int studentId, String major, double balance){
Student collegeStud = new Student(firstName, lastName, studentId, major, balance);
addStudent(collegeStud);
numberOfStudents++;
}
public void addStudent (Student collegeStud) {
studentListArray[numberOfStudents++]=new Student(collegeStud.getFirstName(), collegeStud.getLastName(),
collegeStud.getStudentId(), collegeStud.getMajor(),collegeStud.getBalance());
}
public String toString() {
String result = "";
for (int i=0; i<numberOfStudents; i++) {
result += studentListArray[i].toString() + "\n";
}
return result;
}
public Student[] getList() {
return studentListArray;
}
public int listSize() {
return numberOfStudents;
}
public Student searchForStudent (String firstName){
int index = 0;
while (index < numberOfStudents) {
if (studentListArray[index].equals(new Student(Student.getFirstName(),Student.getLastName(),Student.getStudentId(),Student.getMajor(),Student.getBalance()))) {
return studentListArray[index];
}
index++;
}
return null;
}
public static void main(String args[]) {
StudentList theList = new StudentList();
theList.addStudent (new Student ("John","Sling" ,97, "Maths", 20.00));
theList.addStudent (new Student ("Mike","Versace", 99, "CS",0.00));
theList.addStudent (new Student ("Bob","Tomson" ,57, "Physic",5.00));
//theList.createStudent(new Student(Student.getFirstName(),Student.getLastName(),Student.getStudentId(),Student.getMajor(),Student.getBalance()));
//theList.searchForStudent(new String());
System.out.println (theList.toString());
}
}
The problem is that you marked your fields as static. Remove it and the method will work as expected.
public class Student {
//non-static fields
private String firstName;
private String lastName;
private int studentId;
private String major;
private double balance;
//similar for getters, setters and toString method
}
Static members are shared amongst all objects in a class rather than being one per object. Hence each new object you create is overwriting the data of the previous one.
More info:
What does the 'static' keyword do in a class?

Categories