View Full Version : Problems with arrays of objects

12-27-2005, 04:59 PM
Hey, ok well im trying to create a kind of phone book in java. I have created an array of objects, each as a contact.
This is a snip from my code

public static void main(String[] args) {
for(int i=0; i < nocont; i++){
mycontact[i] = new Contact(); System.out.println("New Contact"); System.out.print("\nEnter First Name: "); mycontact[i].firstname = UserInput.readString(); int lenfirst = mycontact[i].firstname.length(); if (lenfirst == 0){ System.out.println("ERROR, No first name was entered\n");

The array is 3 in length. The problem is, when you enter the first name, it fills all the array up with the firstname. Therefore you get no unique contacts they are all the very last one you input.

Any help would be greatly accepted!

12-27-2005, 05:24 PM
Is there javascript or java language what you are looking for?

12-27-2005, 06:44 PM
Ok, well ive realised that my original post isnt easy to understand so ive changed it and reduced my code completely. I just want to put in 3 names into the array of objects and get it to repeat it back to me.

import java.io.*;

public class PhoneBook {

final static int nocont = 3;
static Contact[] array = new Contact[3];

public static void main(String[] args) {

for (int i = 0; i < nocont; i++){
array[i] = new Contact();
System.out.println("Enter first name: ");
array[i].firstname = UserInput.readString();

for(int j = 0; j < nocont; j++)



ok so for example you run the script, and put in the names, john, tom, andrew.
john should be array[0].firstname
tom should be array[1].firstname
andrew should be array[2].firstname

I dont understand why it doesnt print those all out again for you. Instead i get tom repeated 3x
Could you explain what i am doing wrong?

12-28-2005, 09:39 AM
As I have said... Your code is in Java, but here is a Javascript Forum. Java and Javascript have nothing in common... Ask moderator to move this thread to a proper Forum

12-28-2005, 09:58 AM
i see what u mean lol ok thanks

12-28-2005, 10:13 AM
maybe here:

12-28-2005, 01:27 PM
There's also a java section under computer programming...