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 :)
Related
I am new in java and I trying to get information
for five students and save them into an array of classes. how can I do this?
I want to use class person for five students whit different informations
import java.io.IOException;
import java.util.*;
public class exam
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
// I want to get and save information in this array
person[] f = new student[5];
}
}
class person defined for get name and family name.
import java.util.*;
public abstract class person {
Scanner scr = new Scanner(System.in);
private String name , fname;
public void SetName() {
System.out.println("enter name and familyNAme :");
name = scr.next();
}
public String getname() {
return name;
}
public void setfname () {
System.out.println("enter familyname:");
fname = scr.next();
}
public String getfname() {
return fname;
}
}
class student that inherits from the class person for get studentID and student Scores .
import java.util.*;
class student extends person {
float[] p = new float[5];
int id , sum ;
float min;
public void inputs() {
System.out.println("enter the id :");
id = scr.nextInt();
}
public void sumation() {
System.out.println("enter points of student:");
sum= 0;
for(int i = 0 ; i<5 ; i++){
p[i]=scr.nextFloat();
sum+=p[i];
}
}
public void miangin() {
min = (float)sum/4;
}
}
So first things first, when creating Java objects, refrain from getting input inside the object so that if you decide to change the way you get input (e.g. transition from command line to GUI) you don't need to modify the Java object.
Second, getters and setters should only get or set. This would save some confusion when debugging since we don't have to check these methods/functions.
So here's the person object:
public abstract class Person {
protected String name, fname;
public Person (String name, String fname) {
this.name = name;
this.fname = fname;
}
public void setName (String name) {
this.name = name;
}
public String getName () {
return name;
}
public void setFname (String fname) {
this.fname = fname;
}
public String getFname () {
return fname;
}
}
And here's the student object (tip: you can make as much constructors as you want to make object creation easier for you):
public class Student extends Person {
private float[] p;
private int id;
public Student (String name, String fname) {
this (name, fname, -1, null);
}
public Student (String name, String fname, int id, float[] p) {
super (name, fname);
this.id = id;
this.p = p;
}
public void setP (float[] p) {
this.p = p;
}
public float[] getP () {
return p;
}
public void setId (int id) {
this.id = id;
}
public int getId () {
return id;
}
public float summation () {
float sum = 0;
for (int i = 0; i < p.length; i++)
sum += p[i];
return sum;
}
public float miangin () {
return summation () / 4.0f;
}
#Override
public String toString () {
return new StringBuilder ()
.append ("Name: ").append (name)
.append (" Family name: ").append (fname)
.append (" Id: ").append (id)
.append (" min: ").append (miangin ())
.toString ();
}
}
And lastly, wherever your main method is, that is where you should get input from. Take note that when you make an array, each index is initialized to null so you still need to instantiate each array index before using. I made a sample below but you can modify it depending on what you need.
import java.util.*;
public class Exam {
Scanner sc;
Person[] people;
Exam () {
sc = new Scanner (System.in);
people = new Person[5];
}
public void getInput () {
for (int i = 0; i < people.length; i++) {
System.out.print ("Enter name: ");
String name = sc.nextLine ();
System.out.print ("Enter family name: ");
String fname = sc.nextLine ();
System.out.print ("Enter id: ");
int id = sc.nextInt (); sc.nextLine ();
System.out.println ("Enter points: ");
float[] points = new float[5];
for (int j = 0; j < points.length; j++) {
System.out.printf ("[%d] ", j + 1);
points[j] = sc.nextFloat (); sc.nextLine ();
}
people[i] = new Student (name, fname, id, points);
}
}
public void printInput () {
for (Person p: people)
System.out.println (p);
}
public void run () {
getInput ();
printInput ();
}
public static void main (String[] args) {
new Exam ().run ();
}
}
Just one last tip, if you ever need dynamic arrays in Java, check out ArrayList.
You can add a class attribute, and then add class information for each student, or you can add a class class, define an array of students in the class class, and add an add student attribute, and you can add students to that class.
First of all, please write class names with capital letter (Student, Exam <...>).
Exam class:
import java.util.Scanner;
public class Exam {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Student[] students = new Student[]{
new Student(),
new Student(),
new Student(),
new Student(),
new Student()
};
for (int i = 0; i < 5; i++) {
students[i].setFirstName();
students[i].setLastName();
students[i].setId();
}
}
}
Person class:
import java.util.Scanner;
public class Person {
String firstName, lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName() {
System.out.println("Type firstName: ");
this.firstName = new Scanner(System.in).next();
}
public String getLastName() {
return lastName;
}
public void setLastName() {
System.out.println("Type lastName: ");
this.lastName = new Scanner(System.in).next();
}
}
Student class:
import java.util.Scanner;
public class Student extends Person{
int id;
public int getId() {
return id;
}
public void setId() {
//Converting String line into Integer by Integer.parseInt(String s)
System.out.println("Type id: ");
this.id = Integer.parseInt(new Scanner(System.in).next());
}
}
I've created the class Course which contains the array students. This array contains student names which are in string form.
My new goal is to convert from an Array to an ArrayList. I'm not really sure how to go about this. I've read up on ArrayList and I believe it's resize-able which I think would work well in this case given the fact that the number of students might change constantly with my dropSutdent and addStudent method as opposed to setting an array size to 100, but only having 20 students.
I'd really appreciate and explanations/suggestions of how exactly to change to an ArrayList instead of an Array.
Note I apologize for any mistakes or if I left something unclear. This is my first question on StackOverflow and I know you guys are pretty strict on question asking, so I apologize in advance.*
class Course {
private String courseName;
private String[] students = new String[100];
private int numberOfStudents;
public Course(String courseName) {
this.courseName = courseName;
}
public void addStudent(String student) {
int add = numberOfStudents - students.length; //Create integer to find how many slots we need
if (numberOfStudents > students.length) { //if # of students is bigger then size of array,
String[] array = new String[students.length + add]; //then we add slots to the array.
System.arraycopy(students, 0, array, 0, students.length); //copy array
students = array;
}
students[numberOfStudents++] = student; //add student.
}
public String[] getStudents() {
return students;
}
public int getNumberOfStudents() {
return numberOfStudents;
}
public String getCourseName() {
return courseName;
}
public void dropStudent(String student) {
for (int i = 0; i < students.length; i++) {
if (student == (students[i])) { //If student matches the student we want to remove.
numberOfStudents--; //remove student
while (i < numberOfStudents) {
students[i] = students[i+1];
i++;
}
}
}
}
public void clear() {
students = new String[1]; //set size to 1
numberOfStudents--; //remove all students
}
}
List handles resizing internally, which means you can remove most of the boilerplate by using it instead of an array.
class Course {
private String courseName;
private List<String> students = new ArrayList<>();
public Course(String courseName) {
this.courseName = courseName;
}
public void addStudent(String student) {
students.add(student);
}
public List<String> getStudents() {
return students;
}
public int getNumberOfStudents() {
return students.size();
}
public String getCourseName() {
return courseName;
}
public void dropStudent(String student) {
while (students.remove(student));
}
public void clear() {
students.clear();
}
}
ArrayLists are really usefull, but if you need more options, you can always create a class that works like list and implement all the methods as you wish.
Example for students:
public class studentList{
int size;
Student [] list;
public studentList()
{
size = 0;
list = new Student[size];
}
public studentList(int size)
{
this.size = size;
list = new Student[size];
}
public void add(Student s)
{
}
public void remove(Student s)
{
}
public void sort()
{
}
}
You can implement as you wish.
I have two classes; Course and Student classes. One of the fields in the Student class is a course. When i run this program, I fail to hold a course object in the declared array. The code below will give more light where things are failing:
package school;
public class Course
{
private String courseName;
private String courseGrade;
int counter;
public Course()
{
courseName="";
courseGrade="";
counter = 0;
}
public Course (String name,String grade)
{
courseName=name;
courseGrade=grade;
counter=0;
}
public String getCourseName()
{
return courseName;
}
public String getCourseGrade()
{
return courseGrade;
}
public void setCourse(String name,String grade)
{
courseName=name;
courseGrade=grade;
counter++;
}
#Override
public String toString ()
{
return String.format("%-10s %-10s", courseName,courseGrade);
}
}
package school;
public class Student
{
private String firstName;
private String lastName;
private int counter;
private Course [] myCourse;
public Student ()
{
firstName="";
lastName="";
myCourse =new Course[2];
for (int i=0;i<2;i++)
{
myCourse [i]= new Course ();
}
counter= 0;
}
public Student(String first,String last)
{
firstName=first;
lastName=last;
myCourse =new Course[2];
for (int i=0;i<2;i++)
{
myCourse [i]= new Course ();
}
counter= 0;
}
public Student(String first,String last, Course [] newCourse)
{
firstName=first;
lastName=last;
myCourse= new Course [2];
for (int i=0;i<2;i++)
{
myCourse [i]= new Course ();
}
counter++;
}
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public int getNumberOfCourses()
{
return counter;
}
public void setStudent(String first,String last, Course [] newCourse)
{
firstName=first;
lastName=last;
myCourse= new Course [2];
for (int i=0;i<2;i++)
{
myCourse [i]= newCourse[i];
}
counter++;
}
public void setStudent(String first,String last)
{
firstName=first;
lastName=last;
}
public void registerCourses(Course newCourse)
{
for (int i=0;i<2;i++)
{
myCourse[i]=newCourse;
}
counter++;
}
public String toString()
{
String getString;
getString =(firstName+" "+lastName);
for(int i=0;i<2;i++)
{
getString=getString+String.format("%n %-10s",myCourse[i]);
}
return getString;
}
}
package school;
import java.util.*;
public class Test
{
static Scanner cin= new Scanner(System.in);
public static void main(String[] args)
{
String first,last,name,grade;
Student [] myStudent= new Student [2];
Course [] myCourse= new Course [2];
for (int i=0;i<2;i++)
{
myStudent[i] = new Student();
System.out.println("enter name:");
first=cin.next();
System.out.println("Last Name:");
last=cin.next();
// For loop within a for loop
for (int j=0;j<2;j++)
{
myCourse [j]= new Course ();
System.out.println("Course Name:");
name=cin.next();
System.out.println("Course Grade:");
grade=cin.next();
myCourse [j] = new Course(name,grade);
myStudent[i].registerCourses(myCourse [j]);
}
myStudent [i]=new Student(first, last, myCourse);
}
for (int i=0;i<2;i++)
{
System.out.println(myStudent[i]);
}
}
}
the problem is in the second for loop which is unable to hold course object that i want it to.
I want the program to output something similar to the following:
Student One
MAT A
PHY B
BIO C
CHE A
LAN A+
HIS A
Student Two
COM C
Statistics A+
COM C
Mathematics D
Geography A
Biology C+
Student Three
Biology C
Mathematics D
LAN A+
COM B
Physics B
Physics B
However I am unable to obtain that output. In fact i get the following output:
enter name:
Student
Last Name:
One
Course Name:
MAT
Course Grade:
A
Course Name:
COM
Course Grade:
C
enter name:
Student
Last Name:
Two
Course Name:
STA
Course Grade:
A
Course Name:
ENG
Course Grade:
B
Student One
Student Two
you are destroying the first myStudent[i] data when performing a new on the same index at the end of your loop:
for (int i=0;i<2;i++)
{
myStudent[i] = new Student();
<some code>
myStudent [i]=new Student(first, last, myCourse);
Since you have an undefined number of courses I would suggest using ArrayList and then you do
Also, think what you are doing here.
public void registerCourses(Course newCourse)
{
for (int i=0;i<2;i++)
{
myCourse[i]=newCourse;
}
counter++;
}
You are adding one course and then saying for each position for a course in my array add the new course I was given
You should either use an index, or use an arraylist, or linkedlist etc.
E.g.
public void registerCourses(Course newCourse, int index)
{
myCourse[index]=newCourse;
}
or
public void registerCourses(Course newCourse)
{
myCourse.push(newCourse); // that is given myCourse is an ArrayList<Course>
}
Check the registerCourses method inside Student class. It seems its overriding your result on a same index.
You can do that with List and keep adding that.
Here is the one I updated Student Class.
package com.stack;
import java.util.ArrayList;
import java.util.List;
public class Student
{
private String firstName;
private String lastName;
private int counter;
private List<Course> myCourse;
public Student ()
{
firstName="";
lastName="";
myCourse =new ArrayList<Course>();
counter= 0;
}
public Student(String first,String last)
{
firstName=first;
lastName=last;
myCourse =new ArrayList<Course>();
counter= 0;
}
public Student(String first,String last, List<Course> newCourse)
{
firstName=first;
lastName=last;
myCourse= newCourse;
counter++;
}
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public int getNumberOfCourses()
{
return counter;
}
public void setStudent(String first,String last, List<Course> newCourse)
{
firstName=first;
lastName=last;
myCourse= newCourse;
counter++;
}
public void setStudent(String first,String last)
{
firstName=first;
lastName=last;
}
public void registerCourses(Course newCourse)
{
myCourse.add(newCourse);
counter++;
}
public String toString()
{
String getString;
getString =(firstName+" "+lastName);
for(int i=0;i<2;i++)
{
getString=getString+String.format("%n %-10s",myCourse.get(i));
}
return getString;
}
}
Test Class:
package com.stack;
import java.util.*;
public class Test
{
static Scanner cin= new Scanner(System.in);
public static void main(String[] args)
{
String first,last,name,grade;
Student [] myStudent= new Student [2];
List<Course> myCourse= new ArrayList<Course>();
for (int i=0;i<2;i++)
{
myStudent[i] = new Student();
System.out.println("enter name:");
first=cin.next();
System.out.println("Last Name:");
last=cin.next();
// For loop within a for loop
for (int j=0;j<2;j++)
{
System.out.println("Course Name:");
name=cin.next();
System.out.println("Course Grade:");
grade=cin.next();
Course myC = new Course(name,grade);
myCourse.add(myC);
myStudent[i].registerCourses(myC);
}
myStudent [i]=new Student(first, last, myCourse);
}
for (int i=0;i<2;i++)
{
System.out.println(myStudent[i]);
}
}
}
Note: For 3 Students, you need to iterate loop until i<3 (not 2).
I'm making a program to display the names, ages and gpa's of a class which has been stored in an array. I made the Student class with a constructor, accessors and a method to print out the details.
In the main method, I populate the array and want to display all of the items in the array (this is what I'm having trouble with).
This is what I have so far:
public class Student {
private String name;
private int age;
private double gpa;
public Student(String studentName, int studentAge, double studentGpa) {
this.name = studentName;
this.age = studentAge;
this.gpa = studentGpa;
}
//Normal accessors, not going to bother putting them on here.
public void printStudents() {
System.out.println("Name: " + name + ", Age: " + age + ", GPA: " + gpa);
}
//New class, imagine it's on a different file
public class MyClass {
private static Student [] students = new Student[3];
System.out.println("Students in my class");
students[0] = new Student("Mark",16,77.6);
students[1] = new Student("Sam",17,56.9);
students[2] = new Student("Polly",16,97.4);
for (int g = 0; g < students.length; g++) {
//This is where I'm stuck, I'm not sure how to call printStudents here. students.printStudents didn't work for some reason.
class Student {
private String name;
private int age;
private double gpa;
public Student(String studentName, int studentAge, double studentGpa) {
this.name = studentName;
this.age = studentAge;
this.gpa = studentGpa;
}
public void printStudent() {
System.out.println("Name : "+this.name);
System.out.println("Age : "+this.age);
System.out.println("GPA : "+this.gpa);
}
}
public class MyClass {
public static void main(String s[])
{
Student [] students = new Student[3];
System.out.println("Students in my class");
students[0] = new Student("Mark",16,77.6);
students[1] = new Student("Sam",17,56.9);
students[2] = new Student("Polly",16,97.4);
for (int i = 0; i <=(students.length-1); i++) {
students[i].printStudent();
}
}
}
As #Hello_World mentioned in the comments - change printStudents method name to printStudent to make more sense. It is a public method of the Student object, which means you access it directly from the instance of the object (for example students[0].printStudent()). Also you can iterate through an Array with a foreach cycle, which is a bit easier to read.
students[0] = new Student("Mark", 16, 77.6);
students[1] = new Student("Sam", 17, 56.9);
students[2] = new Student("Polly", 16, 97.4);
for (Student student : students) {
student.printStudent();
}
Im creating a program that is supposed have the user enter a student name and see if it exist in the student array using a linear search method. The student array is in a different class and im having trouble creating a constructor i have tried many things and its not working can someone point me in the right direction.
My linear search class is
import java.util.*;
import java.util.Scanner;
public class LinearSearch {
public int find(Student [] a, String nm) {
for (int i = 0; i < a.length; i++) {
if (a[i].equals(nm)){
return i;
break;
}
else{
return -1;
}
}
}
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
LinearSearch search = new LinearSearch();
Student stu = new Student();
Student [] arr = stu.getArray();
System.out.print("Enter the name to search: ");
String name = reader.nextLine();
int n = search.find(arr, name);
if ((n >= 0) && (n < arr.length)) {
System.out.println(name + " was found at index: " + n);
} else {
System.out.println(name + " was not found");
}
}
}
My Student class is
import java.util.*;
public class Student {
public Student(){
}
public Student [] getArray(){
Student [] studentArray = new Student[3];
studentArray[0] = new Student ("Mel");
studentArray[1] = new Student ("Jared");
studentArray[2] = new Student ("Mikey");
return studentArray;
}
}
You defined a constructor with no argument:
public Student() {
}
But you're invoking a constructor which needs a String as argument:
studentArray[0] = new Student("Mel");
So, your constructor should have a String as argument:
public Student(String name)
And you should probably store this name as a field in the Student class:
private String name;
public Student(String name) {
this.name = name;
}
Note that there is no way that a Student instance could be equal to a String instance. You should provide a getter method for the name, and compare the entered String with the name of the student, instead of comparing it with the student itself.
import java.util.*;
public class Student {
private String name;
public Student(String name){
this.name = name;
}
public Student [] getArray(){
Student [] studentArray = new Student[3];
studentArray[0] = new Student ("Mel");
studentArray[1] = new Student ("Jared");
studentArray[2] = new Student ("Mikey");
return studentArray;
}
public String getName(){
return name;
}
}
and of course in the compersion you'll need to do:
f (a[i].getName().equals(nm)){
public class Student {
private String studentName;
private Student[] studentArray;
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public Student[] getStudentArray() {
return studentArray;
}
public void setStudentArray(Student[] studentArray) {
this.studentArray = studentArray;
}
public Student(){
studentArray = new Student[3];
}
public Student[] getArray() {
Student st1 = new Student();
st1.setStudentName("mel");
Student st2 = new Student();
st2.setStudentName("Jared");
Student st3 = new Student();
st3.setStudentName("Mikey");
studentArray[0]=st1;
studentArray[1]=st2;
studentArray[2]=st3;
return studentArray;
}
}
the above code is your Student class. there is no need to create a constructor though. but because you would like it i put it in the code.
the LinearSearch class is as follow:
public class LinearSearch {
private int i;
public int find(Student[] a, String nm) {
for ( i = 0; i < a.length; i++) {
if (a[i].getStudentName().equals(nm)) {
break;
} else {
i = -1;
}
}
return i;
}
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
LinearSearch search = new LinearSearch();
Student stu = new Student();
Student[] arr = stu.getArray();
System.out.print("Enter the name to search: ");
String name = reader.nextLine();
int n = search.find(arr, name);
if ((n >= 0) && (n < arr.length)) {
System.out.println(name + " was found at index: " + n);
} else {
System.out.println(name + " was not found");
}
}
}