// Fig. 1.3: Student.java
// Student class definition
public class Student
{
// A student's personal details
private String name;
private int age;
// Student constructor initialises each instance variable
public Student(String nameIn, int ageIn)
{
name = nameIn;
age = ageIn;
}
// Return a student's name
public String getName() { return name; }
// Return a student's age
public int getAge() { return age; }
}// end of class Student
// Fig. 1.3: ArrayStudent.java
// Application Class ArrayStudent is a testbed for class Student
import java.io.*;
public class ArrayStudent
{
// keyboard input
static BufferedReader keyboard = new BufferedReader(
new InputStreamReader(System.in));
public static void main(String args[] )throws IOException
{
String name;
int age, number;
System.out.print("How many students? ");
number = Integer.parseInt(keyboard.readLine());
Student s[] = new Student[number];
// input into the array
for(int index = 0; index < number; index++)
{
System.out.println();
System.out.print("Enter Name of student number " + (index+1) + "? ");
name = keyboard.readLine();
System.out.print("Enter Age for " + name + "? ");
age = Integer.parseInt(keyboard.readLine());
s[index] = new Student(name,age);
}
printArray(s);
}// end of main
// Prints elements of array - "Student objects"
private static void printArray(Student s[])
{
System.out.println("Student List:");
for(int index = 0; index < s.length; index++)
{
System.out.println(s[index].getName() + " " + s[index].getAge());
}
}// end of method printArray
// Finding the average age.
private static double findAverage(Student s[])
{
double sum = 0.0;
for(int i = 0; i < s.length; i++)
{
sum += s[i].getAge();
return sum / s.length;
}
System.out.println("The total average age is" + findAverage(s));
}
}// end of class ArrayStudent

New Topic/Question
Reply



MultiQuote




|