aspose file tools*
The moose likes Beginning Java and the fly likes retrieving array Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "retrieving array" Watch "retrieving array" New topic
Author

retrieving array

Martyn Clark
Ranch Hand

Joined: Apr 16, 2005
Posts: 108
Hi
When i run this program it only prints to the screen the last name and course enterd, it all compiles ok, could somebody have a look at the code for me and if possible point out where i have gone wrong.

public class Student
{
// Private members
private String name;

private String course;

// constructor for new student object
public Student(String newStudent, String newCourse)
{
name = newStudent;
course = newCourse;
}

// methods for retrieving name and course
public String getName()
{
return name;
}

public String getCourse()
{
return course;
}

}

public class Storage
{
// private members
private Student[] students;

private int maxNum;

// constructor for new student array
public Storage(int numOfStudents)
{
students = new Student[numOfStudents];
maxNum = numOfStudents;
}
//method for adding student to array
public void addStudent(Student studentObject)
{
for(int i=0; i<students.length; i++)
students[i]= studentObject;
}
public int getSize()
{
return students.length;
}
//display the results of the students list
public void displayAll()
{
System.out.println("Studnets names\tStudents courses");
for(int i=0; i<getSize(); i++)
{
System.out.println(students[i].getName() + "\t\t" + students[i].getCourse());
}
}

}

import javax.swing.*;
public class Main
{

/**
* @param args
*/
public static void main(String[] args)
{
int maxNum = 5;
Storage store = new Storage(maxNum);
for(int i=0; i<store.getSize()-1; i++)
{
String name= JOptionPane.showInputDialog("please enter a name!");
String course = JOptionPane.showInputDialog("please enter a course");
Student newStudent = new Student(name, course);
store.addStudent(newStudent);
}
store.displayAll();

}

}

much appriciated.


Martyn...<br /> <br />SCJP 1.4 SCWCD 1.4
Nigel Browne
Ranch Hand

Joined: May 15, 2001
Posts: 673
The reason this is happening is because the logic is incorrect in this method
Each time your enter a student you fill every space in your array with the newly created student.
Martyn Clark
Ranch Hand

Joined: Apr 16, 2005
Posts: 108
Thanks for pointing the problem out for me nigel
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: retrieving array