Having trouble printing my array of objects - java

I am trying to write an application that takes in a user specified number, then makes that many objects (I am calling them Students) assigns a random name and number to them then sorts their numbers. I have the sorts worked out but am having issues with printing the array. My code is below. The output that I am getting is "New Object" the number of times I enter, followed by "0: null" for each of me toString calls. Any help would be greatly appreciated. Thank you.
import java.util.Random;
import java.util.Scanner;
public class application {
public static void main(String[] args) {
int studentSerialNumber;
String studentName;
System.out.println("Enter the number of students you would like to sort: ");
Scanner scanner = new Scanner(System.in);
int numOfStudents = scanner.nextInt();
Student[] anArrayToSort = new Student[numOfStudents];
for (int i = 0; i < anArrayToSort.length; i++) {
studentSerialNumber = ((int)(Math.random() * 8888)) + 1000;
studentName = getStudentName();
anArrayToSort[i] = new Student(studentSerialNumber, studentName);
}
for (int i = 0; i < anArrayToSort.length; i++) {
System.out.println(anArrayToSort[i].toString());
}
}
private static String getStudentName() {
String studentName = "";
int i = 7;
Random r = new Random();
while (i > 0) {
char c = (char) (r.nextInt(26) + 'a');
studentName = studentName + c;
i--;
}
return studentName;
}
}
public class Student {
int studentSerialNumber;
String studentName;
Student(int studentSerialNumber, String studentName) {
studentSerialNumber = studentSerialNumber;
studentName = studentName;
System.out.println("New Object");
}
public String toString() {
return studentSerialNumber + ": " + studentName;
}
}

Assignments in constructor are bad:
Student(int studentSerialNumber, String studentName) {
studentSerialNumber = studentSerialNumber;
studentName = studentName;
System.out.println("New Object");
}
this should be:
Student(int studentSerialNumber, String studentName) {
this.studentSerialNumber = studentSerialNumber;
this.studentName = studentName;
System.out.println("New Object");
}
Currently you're assigning values to themselves and not to Student instance fields.

Related

Trouble getting input for object array

I am trying to create a class that receives data about a person's name, exam subject, and exam score. I have these classes so far:
APExam:
public class APExam {
//instance variables
private String mySubject;
private int myScore;
//constructors
public APExam(String subject, int score) {
mySubject = subject;
myScore = score;
}
public APExam() {
mySubject = "";
myScore = 1;
}
//getters and setters
public void setSubject(String s) {
mySubject = s;
}
public String getSubject() {
return mySubject;
}
public void setScore(int score) {
myScore = score;
}
public int getScore() {
return myScore;
}
//compareTo
public String compareTo(int s) {
if(myScore == s)
return "Scores are equal.";
else if(myScore > s)
return "The first score is greater than the second score.";
else
return "The second score is greater than the first score.";
}
//equals
public boolean equals(String str) {
return mySubject.equals(str);
}
//toString
public String toString() {
return "Subject: " + mySubject + "\nScore: " + myScore;
}
}
APStudent:
public class APStudent {
//instance variables
private String myFirstName;
private String myLastName;
private ArrayList<APExam> myExams = new ArrayList<APExam>();
//constructors
public APStudent(String fname, String lname) {
myFirstName = fname;
myLastName = lname;
}
public APStudent() {
myFirstName = "";
myLastName = "";
}
//getters and setters
public void setFirstName(String fname) {
myFirstName = fname;
}
public String getFirstName() {
return myFirstName;
}
public void setLastName(String lname) {
myLastName = lname;
}
public String getLastName() {
return myLastName;
}
public ArrayList<APExam> getExams() {
return myExams;
}
//addExam
public void addExam(APExam ex) {
myExams.add(ex);
}
//computeExamAverage
public double computeExamAverage(List<APExam> exams) {
int sum = 0;
for(int i = 0; i < exams.size(); i++) {
sum += exams.get(i).getScore();
}
return (double) sum / exams.size();
}
//findHighestExamScore
public int findHighestExamScore(List<APExam> exams) {
int max = exams.get(0).getScore();
for(APExam ex : exams) {
if(ex.getScore() > max) {
max = ex.getScore();
}
}
return max;
}
//numberOfFives
public int numberOfFives(List<APExam> exams) {
int fiveCount = 0;
for(APExam ex : exams) {
if(ex.getScore() == 5) {
fiveCount++;
}
}
return fiveCount;
}
}
ArrayListTest:
public class ArrayListTest {
public static void main(String[] args) {
//instance variables
final String QUIT = "end";
Scanner sc = new Scanner(System.in);
ArrayList<APExam> myExams = new ArrayList<APExam>();
APStudent student = new APStudent();
String fname, lname, sub, input = "";
int score;
//prompt for info
System.out.print("Enter first name: ");
fname = sc.nextLine();
student.setFirstName(fname);
System.out.print("\nEnter last name: ");
lname = sc.nextLine();
student.setLastName(lname);
while(!input.equals(QUIT)) {
APExam ap = new APExam();
System.out.print("\nEnter exam subject or 'end' to quit: ");
input = sc.nextLine();
sub = input;
ap.setSubject(sub);
System.out.print("\nEnter exam score: ");
score = sc.nextInt();
ap.setScore(score);
student.addExam(ap);
sc.nextLine();
}
//display information
System.out.println(student.getExams());
System.out.println("Name: " + student.getFirstName() + " " + student.getLastName());
System.out.println("Exam average score: " + student.computeExamAverage(myExams));
System.out.println("Highest score: " + student.findHighestExamScore(myExams));
System.out.println("Number of fives: " + student.numberOfFives(myExams));
System.out.println();
for(int i = 0; i < myExams.size(); i++) {
System.out.println(myExams.get(i));
}
//prompt for search
System.out.println("1 sequential search"
+ "\n2 binary search"
+ "\n3 exit");
input = sc.nextLine();
while(!((input.equals("1") || input.equals("2") || input.equals("3")))) {
switch(input) {
case "1":
sequentialSearch(myExams, 3);
break;
case "2":
binarySearch(myExams, 2);
break;
case "3":
break;
}
}
}
}
For some reason in the ArrayListTest class it doesn't create an APExam object with the inputted scores and subjects. Is there something wrong with the while loop? Or is something else wrong?
Your problem is that you are for some reason passing variable List<APExam> exams into your functions. When you are doing that you are passing a empty ArrayList<APExam> and that's why it throws a IndexOutOfBoundsException.
You shouldn't pass anything and just use the APStudent's myExams list.
public double computeExamAverage() {
double sum = 0;
for (APExam myExam : myExams) {
sum += myExam.getScore();
}
return sum / myExams.size();
}
public int findHighestExamScore() {
int max = 0;
for(APExam exam : myExams) {
if(exam.getScore() > max) max = exam.getScore();
}
return max;
}
public int numberOfFives() {
return (int) myExams.stream().filter(apExam -> apExam.getScore() == 5).count();
}
EDIT: I would like to comment on your main method too. You should use the parametrized constructors instead of default one and setters. And you should check on the input being "end" before you ask for grade.
public static void main(String[] args) {
final String QUIT = "end"; // not really necessary, but ok
Scanner sc = new Scanner(System.in);
String firstName, lastName, subject;
int score;
//prompt for info
System.out.print("Enter first name: ");
firstName = sc.nextLine();
System.out.print("\nEnter last name: ");
lastName = sc.nextLine();
APStudent student = new APStudent(firstName, lastName); // use of parametrized constructor
while(true) {
System.out.print("\nEnter exam subject or 'end' to quit: ");
subject = sc.nextLine();
if (subject.equals(QUIT)) break; // check if user wants to end it
System.out.print("\nEnter exam score: ");
score = sc.nextInt();
student.addExam(new APExam(subject, score)); // use of parametrized constructor
sc.nextLine();
}
sc.close(); // never forget to close Scanner
//display information etc.
}

Java passing class array into array

I am a student and looking for help with an assignment. Here is the task: Create a CollegeCourse class. The class contains fields for the course ID (for example, “CIS 210”), credit hours (for example, 3), and a letter grade (for example, ‘A’).
Include get() and set()methods for each field. Create a Student class containing an ID number and an array of five CollegeCourse objects. Create a get() and set() method for the Student ID number. Also create a get() method that returns one of the Student’s CollegeCourses; the method takes an integer argument and returns the CollegeCourse in that position (0 through 4). Next, create a set() method that sets the value of one of the Student’s CollegeCourses; the method takes two arguments—a CollegeCourse and an integer representing the CollegeCourse’s position (0 through 4).
I am getting runtime errors on the second for loop where I am trying to get the data into the course array. It is asking for both the CourseID and Hours in the same line and regardless of what I respond with it I am getting an error, it almost seems like it is trying to get all the arrays variables at the same time. Here is my code which includes three classes. Any help to send me in the right direction is appreciated as I have spent a ton of time already researching to resolve.
public class CollegeCourse {
private String courseId;
private int creditHours;
private char grade;
public CollegeCourse(String id, int hours, char grade)
{
courseId=id;
creditHours = hours;
this.grade = grade;
}
public void setCourseId(String id)
{
courseId = id;//Assign course id to local variable
}
public String getCourseId()
{
return courseId;//Provide access to course id
}
public void setHours(int hours)
{
creditHours = hours;//Assign course id to local variable
}
public int getHours()
{
return creditHours;//Provide access to course id
}
public void setGrade(char grade)
{
this.grade = grade;//Assign course id to local variable
}
public char getGrade()
{
return grade;//Provide access to course id
}
}
Student Class
public class Student {
final int NUM_COURSES = 5;
private int studentId;
private CollegeCourse courseAdd;//Declares a course object
private CollegeCourse[] courses = new CollegeCourse[NUM_COURSES];
//constructor using user input
public Student(int studentId)
{
this.studentId=studentId;
}
public void setStudentId(int id)
{
studentId = id;//Assign course id to local variable
}
public int getStudentId()
{
return studentId;//Provide access to course id
}
public void setCourse(int index, CollegeCourse course)
{
courses[index] = course;
}
public CollegeCourse getCourse(int index)
{
return courses[index];
//do I need code to return the courseId hours, grade
}
}
InputGrades Class
import java.util.Scanner;
public class InputGrades {
public static void main(String[] args) {
final int NUM_STUDENTS = 2;
final int NUM_COURSES = 3;
Student[] students = new Student[NUM_STUDENTS];
int s;//subscript to display the students
int c;//subscript to display courses
int stId;
int csIndex;
String courseId = "";
int hours = 0;
//String gradeInput;
char grade = 'z';
CollegeCourse course = new CollegeCourse(courseId,hours, grade);//not sure if I am handling this correctly
Scanner input = new Scanner(System.in);
for(s = 0; s<NUM_STUDENTS; ++s)
{
students[s] = new Student(s);
System.out.print("Enter ID for student #" + (s+1) + ":");
stId = input.nextInt();
input.nextLine();
students[s].setStudentId(stId);
for(c=0; c < NUM_COURSES; ++c)
{
csIndex=c;
System.out.print("Enter course ID #" + (c+1) + ":");
courseId = input.nextLine();
course.setCourseId(courseId);
System.out.print("Enter hours:");
hours = input.nextInt();
input.nextLine();
course.setHours(hours);
String enteredGrade = "";
while(enteredGrade.length()!=1) {
System.out.print("Enter grade:");
enteredGrade = input.nextLine();
if(enteredGrade.length()==1) {
grade = enteredGrade.charAt(0);
} else {
System.out.println("Type only one character!");
}
}
course.setGrade(grade);
students[s].setCourse(csIndex, course);
}
}
for(s = 0; s<NUM_STUDENTS; ++s)
{
System.out.print("\nStudent# " +
students[s].getStudentId());
System.out.println();
for(c=0;c<NUM_COURSES;++c)
System.out.print(students[s].getCourse(c) + " ");
System.out.println();
}
}
}
After input.nextInt() you need to add one more input.nextLine(); and than you can read grade.
System.out.print("Enter hours:");
hours = input.nextInt();
input.nextLine();
course.setHours(hours);
Why it is needed? See this question: Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
You should add a very simple length validation when you input the grade:
String enteredGrade = "";
while(enteredGrade.length()!=1) {
System.out.print("Enter grade:");
enteredGrade = input.nextLine();
if(enteredGrade.length()==1) {
grade = enteredGrade.charAt(0);
} else {
System.out.println("Type only one character!");
}
}
so the full main class code:
import java.util.Scanner;
/**
* Created by dkis on 2016.10.22..
*/
public class App {
public static void main(String[] args) {
final int NUM_STUDENTS = 10;
final int NUM_COURSES = 5;
Student[] students = new Student[NUM_STUDENTS];
//String name;
int s;//subscript to display the students
int c;//subscript to display courses
int stId;
int csIndex;
String courseId = "";
int hours = 0;
char grade = 'z';
CollegeCourse course = new CollegeCourse(courseId,hours, grade);//not sure if I am handling this correctly
Scanner input = new Scanner(System.in);
for(s = 0; s<NUM_STUDENTS; ++s)
{
students[s] = new Student(s);
System.out.print("Enter ID for student #" + s+1 + ":");
stId = input.nextInt();
input.nextLine();
students[s].setStudentId(stId);
for(c=0; c < NUM_COURSES; ++c)
{
//CollegeCourse course = students[s].getCourse(c);
csIndex=c;
System.out.print("Enter course ID#" + c+1 + ":");
courseId = input.nextLine();
course.setCourseId(courseId);
System.out.print("Enter hours:");
hours = input.nextInt();
input.nextLine();
course.setHours(hours);
String enteredGrade = "";
while(enteredGrade.length()!=1) {
System.out.print("Enter grade:");
enteredGrade = input.nextLine();
if(enteredGrade.length()==1) {
grade = enteredGrade.charAt(0);
} else {
System.out.println("Type only one character!");
}
}
course.setGrade(grade);
students[s].setCourse(csIndex, course);
}
}
for(s = 0; s<NUM_STUDENTS; ++s)
{
System.out.print("\nStudent# " +
students[s].getStudentId());
for(c=0;c<NUM_COURSES;++c)
System.out.print(students[s].getCourse(c) + " ");
System.out.println();
}
}
}

how I display value of Participants who are in both events

Q. Create a class named Participant with fields for a name, age, and street address. Include a constructor that assigns parameter values to each field and a toString() method that returns a String containing all the values.
Also include an equals() method that determines two Participants are equal if they have the same values in all three fields.
Create an application with two arrays of at least 5 Participants each--one holds the Participants in the mini-marathon and the other holds Participants in the diving competition. Prompt the user for Participants who are in both events save the files as Participant.java and TwoEventParticipants.java.*/
Here is my code so far. How do I display the value of Participants who are in both events ?
import javax.swing.JOptionPane;
import java.util.*;
public class TwoEventParticipants {
private static Participant mini[] = new Participant[2];
private static Participant diving[] = new Participant[2];
public static void main(String[] args) {
String name="";;
String add="";
int age=0;
Participant p=new Participant(name, age, add);
Participant p1=new Participant(name, age, add);
setParticipant();
setParticipant1();
displayDetail();
displayDetail1();
//Arrays.sort(p1);
if (p.equals(p1)){
System.out.println(p);
}else{
System.out.println(p1);
}
}
public static void setParticipant(){
for (int x = 0; x < mini.length; x++) {
System.out.println("Enter loan details for customer " + (x + 1) + "...");
//Character loanType=getLoanType();
//String loanType=getLoanType();
String name=getName();
String add=getAdd();
int age=getAge();
System.out.println();
mini[x] = new Participant(name, age, add); //<--- Create the object with the data you collected and put it into your array.
}
}
public static void setParticipant1(){
for (int y = 0; y < diving.length; y++) {
System.out.println("Enter loan details for customer " + (y + 1) + "...");
String name=getName();
String add=getAdd();
int age=getAge();
System.out.println();
diving[y] = new Participant(name, age, add);
}
}
// Participant p=new Participant(name,age,add);
//displayDetails();
// System.out.println( p.toString());
public static void displayDetail() {
// for (int y = 0; y < diving.length; y++) {
System.out.println("Name \tAge \tAddress");
//Participant p=new Participant(name,age,add);
for (int x = 0; x < mini.length; x++) {
System.out.println(mini[x].toString());
// System.out.println(diving[y].toString());
}
}
public static void displayDetail1() {
System.out.println("Name \tAge \tAddress");
for (int y = 0; y < diving.length; y++) {
System.out.println(diving[y].toString());
}
}
public static String getName() {
Scanner sc = new Scanner(System.in);
String name;
System.out.print(" Participant name: ");
return name = sc.next();
}
// System.out.print(" Participant name: ");
// name = sc.next();
public static int getAge() {
int age;
System.out.print(" Enter age ");
Scanner sc=new Scanner(System.in);;
return age= sc.nextInt();
}
public static String getAdd() {
String add;
Scanner sc=new Scanner(System.in);;
System.out.print("Enter Address: ");
return add=sc.next();
}
}
Participant with fields for a name, age, and street address
//
public class Participant {
private String name;
private int age;
private String address;
public Participant(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
#Override
public String toString() {
return name + " " + age + " " + address ;
}
// include an equals() method that determines two Participants are equal
public boolean equals(Participant[] name,Participant[] age,Participant[] add) {
if (this.name.equals(name) && this.address.equals(address)&& age == age){
return true;
}
else{
return false;
}
}
}
This will work for you:
for(Participant p : mini){
if(diving.contain(p)){
System.out.pringtln(p.toString()) ;
}
}

How to fix my Array class

I am trying to figure out how to get my array to run correctly, I know I have to change the array value to an input but I cannot get the program to compile if any one can help that be great.
I am trying to have the program take input for grades and names of students and in the end output their name and grade.
Edit sorry this is my first it posting i have an error
Student.java:60: error: class, interface, or enum expected I am in java 101 so this is why it is such low level java, we only know the basics
import java.util.Scanner;
public class students
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("How many students?: ");
int numofstudents = keyboard.nextInt();
Student s = new Student();
s.setMultipleStudents();
s.toString();
System.out.println("Enter the Grade for the student: ");
int gradeofstudnets = keyboard.nextInt();
}
}
and my second class is
import java.util.Scanner;
public class Student
{
Scanner scan = new Scanner(System.in);
private String name;
private int grade;
private int[] multiplegradeinputs = new int[10];
private String[] multipleStudent = new String[10];
public Student()
{
}
public Student(String n, int g)
{
name = n;
grade = g;
}
public String setMultipleStudents()
{
String n = "";
for(int i = 1; i < multipleStudent.length; i++)
{
System.out.println("Enter student #" + i +" name: " );
n = scan.nextLine();
multipleStudent[i] = n;
}
return null;
}
public String multiplegradeinputs()
{
for(int i = 1; i <multiplegradeinputs.length; i++)
{
System.out.println("Enter the Grade of the student#" + i +" : ");
grade = scan.nextInt();
multiplegradeinputs[i] = grade;
}
} <--- error here
public String toString()
{
String temp = "";
for(int i = 1; i < multipleStudent.length; i++)
{
temp += multipleStudent[i] + " ";
}
return temp;
}
}
Add return statement in your multiplegradeinputs() method:
public String multiplegradeinputs()
{
for(int i = 1; i <multiplegradeinputs.length; i++)
{
System.out.println("Enter the Grade of the student#" + i +" : ");
grade = scan.nextInt();
multiplegradeinputs[i] = grade;
}
return null; //Add this line
}
Or change your methods to void return type if they dont return anything.
Class names have to be capitalized in java, so instead of
public class students
you should write
public class Students
Also instead of writing
keyboard.nextInt();
You should write
Integer.parseInt(keyboard.nextLine());
This is mainly because java is full of bugs and technical specifications that you won't find easily. Let me know if this fixes it for you, since you didn't post the exact error message you got.
As for the error that you pointed out, it's because your function expects a String as a return value no matter what, so either change that to void if you can or return a null string. To do that just add the following line at the very end of the method.
return null;
You should create a Student object which holds the properties of the student, e.g. Name and Grades. You should then store all the student objects in some kind of data structure such as an array list in the students class.
Adding to the answer provided by #hitz
You have a bug in the for loops:
for(int i = 1; i <multiplegradeinputs.length; i++)
for(int i = 1; i < multipleStudent.length; i++)
You will never populated multiplegradeinputs[0] and multipleStudent[0] because you start the loop at index == 1 and thus you will have only 9 student names stored instead of 10.
Change to:
for(int i = 0; i <multiplegradeinputs.length; i++)
for(int i = 0; i < multipleStudent.length; i++)
Remember even though the length in 10, the indices always start with 0 in Java and in your case will end with 9.
import java.util.Scanner;
public class Student
{
Scanner scan = new Scanner(System.in);
private String name;
private int grade;
private int[] multiplegradeinputs = new int[10];
private String[] multipleStudent = new String[10];
public Student()
{
}
public Student(String n, int g)
{
name = n;
grade = g;
}
public String setMultipleStudents()
{
String n = "";
for(int i = 1; i < multipleStudent.length; i++)
{
System.out.println("Enter student #" + i +" name: " );
n = scan.nextLine();
multipleStudent[i] = n;
}
return null;
}
public void multiplegradeinputs()
{
for(int i = 1; i <multiplegradeinputs.length; i++)
{
System.out.println("Enter the Grade of the student#" + i +" : ");
grade = scan.nextInt();
multiplegradeinputs[i] = grade;
}
}
public String toString()
{
String temp = "";
for(int i = 1; i < multipleStudent.length; i++)
{
temp += multipleStudent[i] + " ";
}
return temp;
}
}
this is the 2nd class
import java.util.Scanner;
public class students
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("How many students?: ");
int numofstudents = keyboard.nextInt();
Student s = new Student();
s.setMultipleStudents();
s.toString();
System.out.println("Enter the Grade for the student: ");
int gradeofstudnets = keyboard.nextInt();
}
}
You are missing a return value in the multiplegradeinputs() method.

Print students in an array

I am trying to have the user type in the last name and first name of a student in an array so that I can call the student information and use it in a grade book.
The Student class has a method called Student(String last_name, String first_name)
I cannot figure out how to make it print students in a list such as:
last name, first name
last name, first name
Here is my program so far:
public static void main (String[] args)
{
System.out.println("--------------------------------");
System.out.println("Welcome to the Gradebook Program");
System.out.println("--------------------------------");
System.out.println();
students = GetNumberOfStudents();
//Allocate space for student information
Student student[] = new Student[students];
for (int i = 0; i < students; i++)
{
System.out.println("Student #" + (i+1));
System.out.print("\tEnter last name: ");
student[i] = scan.nextLine();
System.out.print("\tEnter first name: ");
student[i] = scan.nextLine();
}
System.out.println(student[i]);
I expect we would need to see the definition of Student, you have given the constructor but not the getters/setters.
I would expect the printing code to look something like
for (Student s : student) {
System.out.println(s.getLastName() + "," + s.getFirstName());
}
You are also not initialising your Student objects correctly.
Inside the loop you have written I would expect to see
new Student(lastname, firstname);
Here is a soltuion with a student class which looks like in your description.
package test; //change to your package name
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Student{
private String m_LastName;
private String m_FirstName;
private int[] TestScores = new int[3];
//Constructor
public Student(String last, String first) {
m_LastName = last;
m_FirstName = first;
}
//returns firstname
public String firstName() {
return m_FirstName;
}
//returns lastname
public String lastName() {
return m_LastName;
}
//set a test score at a given index
public void setTestScore(int index, int score) {
TestScores[index] = score;
}
//returns test score at a given index
public int testScore(int index) {
return TestScores[index];
}
//returns testscores average
public double testAverage() {
int sum = 0;
for(int i = 0; i<TestScores.length; i++) {
sum += TestScores[i];
}
return sum/TestScores.length;
}
//returns students highest test score
public int maxTestScore() {
//sort the array
for(int i = 0; i<TestScores.length; i++) {
for(int j = 0; j<TestScores.length; j++) {
if(TestScores[i]<TestScores[j]) {
int buffer;
buffer = TestScores[i];
TestScores[i] = TestScores[j];
TestScores[j] = buffer;
}
}
}
return TestScores[TestScores.length-1];
}
public boolean isPassing() {
//TODO: when hes passing?
return true;
}
public static void main (String[] args)
{
Scanner scan = new Scanner(new InputStreamReader(System.in));
System.out.println("--------------------------------");
System.out.println("Welcome to the Gradebook Program");
System.out.println("--------------------------------");
System.out.println();
/**
* dont know where you declare the students variable
* and how the getnumberofstudents function looks like
*
* students = GetNumberOfStudents();
*/
int students = 1;
List<Student> StudentList = new ArrayList<>(); //creat a list which can store student objects
for (int i = 0; i < students; i++)
{
System.out.println("Student #" + (i+1));
System.out.print("\tEnter last name: ");
String lastname = scan.nextLine(); //store lastname in a variable
System.out.print("\tEnter first name: ");
String firstname = scan.nextLine(); //store firstname in a variable
Student student = new Student(lastname, firstname); //creat new student object with the last and firstname
StudentList.add(student); //add it to the student list
}
//print out all students first and lastnames. here you can add the other data you want to print.
for (int i = 0; i < students; i++)
{
System.out.println("List of all Students:");
System.out.println("Firstname:"+StudentList.get(i).firstName()+" Lastname:"+StudentList.get(i).lastName());
}
}
}

Categories

Resources