Hi there, I am trying to display three Attributes assigned to each "Student" which variables are defined in my 'Student' Class. In my show student class, I can get the user to decide how many Students they would like to add, and i also get the user to input the variables for Name, StudentID and Address. However I would like to display them in the format of void display() in the 'Student Class'.

I know i will have to use a for statement and i am trying to print out the contents of the array that i have stored.

Here is my code:

class Student
{
public String Name;
public String StudentID;
public String Address;

//constructor
public Student(String SName, String SID, String SAdd)
{
Name = SName;
StudentID = SID;
Address = SAdd;
}

//get methods
public String getName()
	{
	return Name;
	}
public String getID()
	{
	return StudentID;
	}
public String getAddress()
	{
	return Address;
	}
	
//set  method
public void setName( String SName)
	{
	Name = SName;
	}

public void setID (String SID)
	{
	StudentID = SID;
	}

public void setAddress (String SAdd)
	{
	Address = SAdd;
	}

//display method
	public void display()
	{
	System.out.println(Name + "\n" + StudentID +
	"\n" + Address + ".");
	
	
	}
}

And my Show Student Class:

import java.util.*;
import javax.swing.*;
import java.util.Scanner;

public class ShowStudent1
{
	public static void main(String[] args)
	{
	// variables from Student
	String Name;
	String StudentID;
	String Address;
	
	// asking the user how many they would like to add
	int choice;
	Student[] StArray;
	
    System.out.print("How many new Students are you going to add: ");
    Scanner in = new Scanner(System.in);
    choice = Integer.parseInt(in.nextLine());
	
	//creating student array of chosen amount
    StArray = new Student[choice];
    
	//asking user for the variables and trying to display them? 
	for (int x = 0; x < StArray.length; x++)
	{
	Name = JOptionPane.showInputDialog("Enter First and Last Name:");
	StudentID = JOptionPane.showInputDialog("Enter StudentID");
	Address = JOptionPane.showInputDialog("Enter Adress"); 
	
	Student[]  Object = new Student[x];	
	StArray[x] = Object[x];
	System.out.println(Object[x]);
	
	}
	
	}
  
}

Thank you

Can you ask specific questions about your program?
Are you asking how to make a loop that indexes through an array and calls methods for the objects that are elements in the array?

Hi, yes that's pretty much what i want to be able to do. After Storing input in the array, want to associate them with the Name, StudentID, Address Variables. Then display them afterwards to show what student the user has created along with its attributes.

Its the last bit of code that im having trouble with:

//creating student array of chosen amount
StArray = new Student[choice];
 
//asking user for the variables and trying to display them?
for (int x = 0; x < StArray.length; x++)
{
Name = JOptionPane.showInputDialog("Enter First and Last Name:");
StudentID = JOptionPane.showInputDialog("Enter StudentID");
Address = JOptionPane.showInputDialog("Enter Adress");
 
Student[] Object = new Student[x];
StArray[x] = Object[x];
System.out.println(Object[x]);
 
}
 
}

the last part is wrong

for (int x = 0; x < StArray.length; x++)
	{
	Name = JOptionPane.showInputDialog("Enter First and Last Name:");
	StudentID = JOptionPane.showInputDialog("Enter StudentID");
	Address = JOptionPane.showInputDialog("Enter Adress"); 
	
	Student[]  Object = new Student[x];	
	StArray[x] = Object[x];
	System.out.println(Object[x]);
	
	}

you have some logical mistakes here:
1. you shouldn't use 'Object' as the name for your array.
2. you create an array each time you run the loop, which you should not do
3. if you have an array with x elements, you can never get the element that can be found on element x. the index of elements start with 0, so the highest possible index is then: x - 1. (do you see what problem you'll have here the first time you go through this for loop?)

try like this:

read number of entries
create an array with number elements
set index to 0
while ( index < arraysize ){
  read info and create object
  set object in array, location = index
}

set index to 0
while ( index < arraysize )
  print elementInfo

Hello, thanks for your reply.

I have tried to implement what you said to the best of my ability:

StArray = new Student[choice];
    int x = 0;
	while ( x < StArray.length ){
	Name = JOptionPane.showInputDialog("Enter First and Last Name:");
	StudentID = JOptionPane.showInputDialog("Enter StudentID");
	Address = JOptionPane.showInputDialog("Enter Adress"); 
	Student person = new Student(Name, StudentID, Address);
	StArray[x] = person;
	}
	
	x = 0;
	while ( x < StArray.length ){
	System.out.println(StArray[x]);
	}
	}

I do not know if this is correct as I am fairly new. However when i run the program now it does not recognise what number i type in now for "How many to add" the program just keeps running through Enter Name, Enter ID, Enter Address unless i CTRL+C it.

Your looping is controlled by the value of x. To get out of the loop, you must change the value of x inside of the loop.

Personally I'd use a for loop because it easily takes care of changing the loop index variable.

that is because you don't change the value of x.

in your for-loop, it was augmented by one in:
for (int x = 0; x < StArray.length; x++)

but in your current code, your x value will always be 0.
either use the for loop, or place

x++;

as last instruction of your while loop (both of them, off course).
The code I showed you was only ment as a bit of pseudo code, not as java syntaxis that has to be followed. There's nothing wrong with using a for loop like you did before.

Oh Ok. Yes that has done it. I see now I wasnt incrementing the value of x. So now it does come up with the correct amount of JOptionPanes.

However I still can't display the results for each student.

//SHOWSTUDENT CLASS
	x = 0;
	while ( x < StArray.length ){
	System.out.println(StArray[x]);
	}
	}

I know its something to do with this from the 'Student' Class, just not sure how to implement it:

//STUDENT CLASS
//display method
	public void display()
	{
	System.out.println(Name + "\n" + StudentID +
	"\n" + Address + ".");
	
	
	}

I'd have to implement "display()" in the show student class somewhere ?

I still can't display the results for each student.

What does this statement print out?
System.out.println(StArray[x]);

Where do you call the Student class's display method? You have to call the method if you want it to be executed.

if you want to print it like that, you'll have to implement a toString()
but, remember, there you'll have the same issue with your x that isn't incrementing.

Sorry for the long delay.

to Norm1: I'm getting a weird Message in my command prompt after typing input into the JOptionPanes:

Student@5543bd5c
Student@52450ebf

Don't know where this is coming from :S

and to Stultuske:
Ok i'll look up toString().
I need the variables that I have entered to be associated with the set/get methods in my Student class. Is this possible?

Student@5543bd5c

That is the String that is returned by the Object class's toString method. It is the name of the class @ and the object's hashcode.

You want to override the Object class's toString method with your own version in the Student class that will return a String that describes the contents of the object.

Edit: Never mind I have tried it and it works, Thank you very much. Its a step forward :D I now need to figure out a way how to edit and delete the data stored in the array :) Lots of work to do.

editing is exactly the same as with any other object, just you should remember to either do it to edit the stored instance, or save the edited instance.

deleting is not that difficult, too, but since you are working with an array, and not a set or a list, you can either delete by setting the value to null, but that may result in problems when you iterate over the array, or you can create a new array (lengt = lengtOfOriginalArray-1) without the element you want to delete

editing is exactly the same as with any other object, just you should remember to either do it to edit the stored instance, or save the edited instance.

deleting is not that difficult, too, but since you are working with an array, and not a set or a list, you can either delete by setting the value to null, but that may result in problems when you iterate over the array, or you can create a new array (lengt = lengtOfOriginalArray-1) without the element you want to delete

Okay thank you, that makes sense. However my overall aim is to create a student record system so each student has certain attributes and the user can add, edit and delete this data.

My program at the moment does accept input and can display them, but loses it after the program ends.

Am i going about it in the wrong way? I have been reading up on ArrayLists but wondering if even if i used them the input data will still not be stored for a later time?

data will still not be stored for a later time

When your program ends everything in the program's memory goes away.
If you want the data available at future times when the program runs, you need to write the data to a place where it will be available later. One place is to a disk file.

When your program ends everything in the program's memory goes away.
If you want the data available at future times when the program runs, you need to write the data to a place where it will be available later. One place is to a disk file.

Oh okay. Can't it be held in another Class? I need to hold the student data ( which i thought my Student.class does) and a class that will handle total overall storage of students. Sorry to ask so many questions.

Can't it be held in another Class

but loses it after the program ends.

When the program ends there is NOTHING left in memory for the program.

Please explain what you want to do and how you want to execute the program. Be sure to explain when you enter the program and when you exit the program and where the data is supposed to be during all this.

When the program ends there is NOTHING left in memory for the program.

Please explain what you want to do and how you want to execute the program. Be sure to explain when you enter the program and when you exit the program and where the data is supposed to be during all this.

I aim to have a record system either Text based or GUI based. I plan to do it text based, however i'm struggling to know how I will be able to store the data that the user has entered to allow the user to keep adding, deleting and editing student information. I am not allowed to use a Database, just allowed array or another data form to hold the information.

So when I enter the program the user can decide if they want to Add/edit/delete data. When the program exits it should save the current amount of students and their data somewhere? so that even once the program has closed, and the program is run again, the students are still there.

Hope this makes sense?

save the current amount of students and their data somewhere?

You will have to write the current data to a file if you want it available later when the program is run again.

Ok that makes sense. How would I implement this into my main program?

Thank you. I will read this up now.

hello, I have been reading that page you sent me, especially homing in on the "Reading, Writing and Creating Files" tutorial.

However when i try some examples such as:

Path logfile = ...;

//Convert the string to a byte array.
String s = ...;
byte data[] = s.getBytes();

try (OutputStream out = new BufferedOutputStream(logfile.newOutputStream(CREATE, APPEND))) {
    ...
    out.write(data, 0, data.length);
} catch (IOException x) {
    System.err.println(x);
}

I get errors saying that it can't find the symbol for CREATE, getbytes, Path, APPEND. I have made sure that i implement the packages at the top:

import java.nio.file.*;
import java.io.*;
import java.util.*;
import java.nio.file.StandardOpenOption.*;


was wondering what this could be?

I get errors

Please post the full text of the errors.

Look at the FileWriter and FileReader classes for doing simple I/O.
You probably do NOT want to try using the classes in the nio packages yet.

I have read up on FileWriter and FileReader and also the use of BufferedReaders/Writers. I have tried them out and created a text file and read the text file and displayed its contents. However when trying to create a text file based on User input using Scanner, I cannot get it to work. I will in the end need to print out the contents of the Array I made in my other program.

I'm using an example:

import java.io.*;

class FileWriterDemo {
	
	public static void main(String args[]) throws Exception {
    String source = "This is a string";
    char buffer[] = new char[source.length()];
    source.getChars(0, source.length(), buffer, 0);
    FileWriter f1 = new FileWriter("file1.txt");
    f1.write(buffer);
    f1.close();
    }
    }

However when trying to implement a scanner into it and print out what the user inputs, i get an error incompatible types as it says it requires an Int but it has found a Scanner.

public static void main(String args[]) throws Exception
{

 
System.out.print("How many new Students are you going to add: ");
Scanner choice = new Scanner(System.in);
choice = Integer.parseInt(in.nextLine());

   String[] Array;
   Array = new String[choice];
	

FileWriter fw = new FileWriter("mytest.txt");
BufferedWriter bw = new BufferedWriter(fw);
bw.write(choice);
bw.close();
fw=null;

it says it requires an Int but it has found a Scanner.

When you get errors please copy and paste the full text here.

requires an int but it has found a Scanner.

The compiler sees a Scanner object where it wants an int variable.
The expression to the right of the = returns an int.
The variable on left of the = is NOT an int.
The compiler wants an int variable on the left to receive the int value from the right of the =.

I have found out today that I do not need to store the data :(. So I was trying to make it too complicated.

The things in the array do not have to be stored once the program terminates.
So all I have to do is add, edit and delete "Students" in the array, and also be able to display all of them or choose which one to display

I am working on a bit of code that I made earlier when looking into get and set methods.

in my Student Class I have this bit of code:

[B][U]MY CONSTRUCTOR [/U][/B]
public GradeBook(String name1, String name2, String name3 )
	{
		fullName = name1;
		courseName = name2;
		addressName = name3;
		
	}

[U][B]OUTPUT GRADES[/B][/U]
public void outputGrades()
	{
		System.out.println( "The Student Records are:\n" );
		
		
		for (int student = 0; student < studentArray.length; student++ )
		{
		System.out.printf( "Student %2d\n", student + 1 );	
			
			for (String test : studentArray[student] ) 
				System.out.printf( "%8s\n", test );
				
				
		}
	}

I want to call this method in my main program however i'm having trouble with it.

Code in main program:

Student[] studentArray = new Student[welcomeMessage]; 
	Name = ("Kevin Smith");
	Course = ("Internet Engineering");
	Address = ("145 Newbury Road");
	Student person = new Student(Name, Course, Address);
	studentArray[0] = person;
	
	person.outputGrades();

The bit i'm having problems with is the last line of code,
studentArray.outputGrades();

I want it to call the outputGrades method from my Student Class and then display the Student 1: with his info about his name, course and address.

However when running the program it gets up to
The Student Records are:

then displays:
exception in thread "main" java.lang.NullPointerException
at Student.outputGrades(Student.java:36)
at StudentTest.main(StudentTest.java:32)

In my main program, do I need to implement the set methods?

i.e something along the lines of:

Student[] studentArray = new Student[welcomeMessage]; 
	Student.setFullName = ("Kevin Smith");

"main" java.lang.NullPointerException
at Student.outputGrades(Student.java:36)

The JVM found a variable with a null value at line 36.
Look at line 36 in the your source and see what variable is null. Then backtrack in the code to see why that variable does not have a valid value.
If you can not tell which variable it is, add a println just before line 36 and print out the values of all the varibles on that line.

Student.setFullName = ("Kevin Smith");

That statement assigns a String (to right of =) to the static variable: setFullName in the Student class.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.