Hi there, I'm fairly new to java and I have a question about creating an array of objects for a class and allowing data entry for each individual object in the array.

I'm a little confused on how to go about doing this correctly.

As of right now I have about half of my project written for just one individual object as opposed to various different ones.

I'll show you, then explain:

import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.Random;

public class Subscriber {
        public String name;
        public String url;
        public String friendsList = "";
    
        public int adClicks = 0;
        public int friendIndex = 1;
        public int subNum = 0;
        
    public static void main(String[] args) {
        
        Subscriber subscriberList[MAX_NUM];
        String anyMore;
        
        StringTokenizer tokenizedList;
        Random generator = new Random();
          
        Scanner keyboard = new Scanner(System.in);
        adClicks = generator.nextInt(100000);
        
        System.out.println("Please enter your friend's name, last name first,"
                + "when prompted.");
        System.out.println();
        
        do
        {
            System.out.println("Name of friend (last name first!): ");
            name = keyboard.nextLine().toUpperCase();
            
            friendsList = friendsList.concat(name);
            
            System.out.println("\nDo you want to enter another name? (Y/N): ");
            anyMore = keyboard.nextLine().toUpperCase();
            
            if (anyMore.equals("Y"))
            {
                friendsList = friendsList.concat(";");
                System.out.println();
                friendIndex ++;
            }
        
        } while(anyMore.equals("Y"));
        
        tokenizedList = new StringTokenizer(friendsList, ";");
        
        System.out.println("\n" + adClicks + " users have clicked on your ads.");
        System.out.println("You have " + friendIndex +" friend(s): ");
        while (tokenizedList.hasMoreTokens())
        {
            System.out.println(tokenizedList.nextToken());
        }

        
    }
}

As you can see I'm trying to create an array of objects for the Subscriber class. I'd like to be able to loop through entering as many subscribers as necessary as well as inputting and storing their data respectively.

I know this is simple stuff, but if you guys wouldn't mind giving me a push in the right direction that would be great. I'm fairly new to Java and programming as a whole (I've done some C++ work, but not much and it's been a while since then).

Thank you!

Recommended Answers

All 9 Replies

You can create an array of objects similar to how you create an array of primitive data.

Subscriber s[]=new Subscriber[10];

The above creates an array of 10 Subscriber objects.

However you should initialize those objects by using any loop .

for(int i=0;i<10;i++)
{
   s[i]=new Subscriber();
}

You can create an array of objects similar to how you create an array of primitive data.

Subscriber s[]=new Subscriber[10];

The above creates an array of 10 Subscriber objects.

However you should initialize those objects by using any loop .

for(int i=0;i<10;i++)
{
   s[i]=new Subscriber();
}

Thank you, that helped a lot! I have now initialized all of the objects, but I am still baffled on how to loop through each individual Subscriber object and have each input their data that is then saved for each of those objects. I know I need another 'for loop' somewhere to loop through each array member (object) until either it reaches the max limit or the user chooses to break the loop.

Sorry if I'm not making much sense, it's a little tough to put into words for some reason. :-/

Here's my current code:

import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.Random;

public class Subscriber {

        public static int MAX_NUM = 100;
        
        public String name;
        public String url;
        public String friendsList = "";
    
        public int friendIndex = 1;
        public int subNum = 0;
        
        Subscriber(String subName, String subUrl, String subFriends, 
                int subClicks, int subIndex, int aSubNum)
        {
            name = subName;
            url = subUrl;
            friendsList = subFriends;
            friendIndex = subIndex;
            subNum = aSubNum;
        }
        
    public static void main(String[] args) {
        
        Subscriber subscriberList[] = new Subscriber[MAX_NUM];
        
        for(int i = 0; i < MAX_NUM ;i++)
        {
            subscriberList[i]= new Subscriber(null, null, null, 0, 0, 0);
        }

        String anyMore;
        int adClicks;
        
        StringTokenizer tokenizedList;
        Random generator = new Random();
          
        Scanner keyboard = new Scanner(System.in);
        adClicks = generator.nextInt(100000);
        
        System.out.println("Please enter your friend's name, last name first,"
                + " when prompted.");
        System.out.println();
        
        do
        {
            System.out.println("Name of friend (last name first!): ");
            name = keyboard.nextLine().toUpperCase();
            
            friendsList = friendsList.concat(name);
            
            System.out.println("\nDo you want to enter another name? (Y/N): ");
            anyMore = keyboard.nextLine().toUpperCase();
            
            if (anyMore.equals("Y"))
            {
                friendsList = friendsList.concat(";");
                System.out.println();
                friendIndex ++;
            }
        
        } while(anyMore.equals("Y"));
        
        tokenizedList = new StringTokenizer(friendsList, ";");
        
        System.out.println("\n" + adClicks + " users have clicked on your ads.");
        System.out.println("You have " + friendIndex +" friend(s): ");
        while (tokenizedList.hasMoreTokens())
        {
            System.out.println(tokenizedList.nextToken());
        }

        
    }
}

That is the correct way to initialize the object array members right?

Thanks again!

Bump.

I'm not sure if this is right:

for(int i = 0; i < MAX_NUM ;i++)
        {
            System.out.println("Enter subscriber name: ");
            name.subscriberList[i] = keyboard.nextLine().toUpperCase();
            System.out.println("Enter subscriber url: ");
            url.subscriberList[i] = keyboard.nextLine().toLowerCase();
        }

Something like that. It loops through each object while asking for data for each, but it doesn't work. It tells me "non-static variable cannot be accessed from a static context." Also, how would I incorporate the concatenation and tokenizer do while loop into that for loop?

I'm so very confused, any extra help would be appreciated!

It tells me "non-static variable cannot be accessed from a static context."

If you moved all your code to the object's constructor, this problem would go away.
Class variables that are non-static can not be reference from a static method without there being an object of the class to use as a reference variable.

If you moved all your code to the object's constructor, this problem would go away.
Class variables that are non-static can not be reference from a static method without there being an object of the class to use as a reference variable.

I wasn't exactly sure what you meant by "moving all your code to the object's constructor," but I did some fiddling around and I realized that the statement:

url.subscriberList[i] = keyboard.nextLine().toLowerCase();

Should be:

subscriberList[i].url = keyboard.nextLine().toLowerCase();

Now I have another problem, my program compiles fine, but it crashes when it reaches the bolded line of code (Yes, I know it's very ugly at the moment):

import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.Random;

public class Subscriber {

        public static int MAX_NUM = 10;
        
        public String name;
        public String url;
        public String friendsList = "";
    
        public int friendIndex = 1;
        
        Subscriber(String subName, String subUrl, String subFriends, 
                int subClicks, int subIndex, int aSubNum)
        {
            name = subName;
            url = subUrl;
            friendsList = subFriends;
            friendIndex = subIndex;
        }
           
        
    public static void main(String[] args) {
        
        Scanner keyboard = new Scanner(System.in);
        String anyMoreSub;
        String anyMore = null;
        String friendName;
        
        int subIndex = 1;
        int adClicks;
        
        StringTokenizer tokenizedList;
        
        Random generator = new Random();
          
        adClicks = generator.nextInt(100000);
        
        Subscriber subscriberList[] = new Subscriber[MAX_NUM];
        
        for(int i = 0; i < MAX_NUM ;i++)
        {
            subscriberList[i] = new Subscriber(null, null, null, 0, 0, 0);
            
        }

        for(int i = 0; i < MAX_NUM ; i++)
        {
                System.out.println("Enter subscriber name: ");
                subscriberList[i].name = keyboard.nextLine().toUpperCase();
                System.out.println("Enter subscriber url: ");
                subscriberList[i].url = keyboard.nextLine().toLowerCase();
                
                System.out.println("Please enter your friend's name, last name first,"
                + " when prompted.");
                System.out.println();
                
                do
                {
                    System.out.println("Name of friend (last name first!): ");
                    [B]subscriberList[i].name = keyboard.nextLine().toUpperCase();[/B] //Problem here on out
            
                    subscriberList[i].friendsList = subscriberList[i].friendsList.concat(subscriberList[i].name);
                    
                    if (anyMore.equals("Y"))
                    {
                        subscriberList[i].friendsList = subscriberList[i].friendsList.concat(";");
                        System.out.println();
                        subscriberList[i].friendIndex ++;
                    }
                    
                } while(anyMore.equals("Y"));
                
                    tokenizedList = new StringTokenizer(subscriberList[i].friendsList, ";");
                    System.out.println("\n" + adClicks + " users have clicked on your ads.");
                    System.out.println("You have " + subscriberList[i].friendIndex +" friend(s): ");
                    while (tokenizedList.hasMoreTokens())
                    {
                        System.out.println(tokenizedList.nextToken());
                    }
                    
                    System.out.println("\nDo you want to enter another name? (Y/N): ");
                    anyMore = keyboard.nextLine().toUpperCase();
                
                System.out.println("\nDo you want to enter another subscriber? "
                    + "(Y/N): ");
                anyMoreSub = keyboard.nextLine().toUpperCase();
                
                if (anyMoreSub.equals("Y"))
                {
                    subIndex++;
                }
                
                else
                {
                    break;
                }
        }
    }
}

My program will crash after entering the subscriber's friend. I haven't a clue why.

Thanks again for all of the help!

My program will crash after entering the subscriber's friend.

Please copy and paste here the full text of the error message.

Please copy and paste here the full text of the error message.

Here you are:

Exception in thread "main" java.lang.NullPointerException
	at Subscriber.main(Subscriber.java:65)
Java Result: 1
BUILD SUCCESSFUL (total time: 9 seconds)

Exception in thread "main" java.lang.NullPointerException
at Subscriber.main(Subscriber.java:65)

At line 65 in your program there is a variable that is null. Look at that line and see which variable is null and then backtrack in your code to see why it does not have a valid non-null value.
If you can not see what variable it is, add a println to print out the value of all the variables on that line to see which one is null.
Something like this:
System.out.println("var1=" + var1 + ", var2=" + var2 + ....

replace var1 etc with the variables used in your code

At line 65 in your program there is a variable that is null. Look at that line and see which variable is null and then backtrack in your code to see why it does not have a valid non-null value.
If you can not see what variable it is, add a println to print out the value of all the variables on that line to see which one is null.
Something like this:
System.out.println("var1=" + var1 + ", var2=" + var2 + ....

replace var1 etc with the variables used in your code

Oh sheesh! I was setting the String variables equal to 'null' when they should be '""'!

Thank you!

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.