Hey guys! I'm trying to create a program that first asks the user for an integer input n. The program will then ask the user for n Strings and store these in the array. This is what I have so far:

    public static void main (String args[]){
    String[] strArray;
    int num; 
    Scanner sc = new Scanner(System.in); 

    System.out.print("Enter an integer: ");
    num = sc.nextInt();

    for(int i = 0; i < num; i++){
        System.out.print("Enter String: ");
        String str = sc.next(); 
        strArray[0] = str; 
    }
    System.out.print(strArray[0]);
    }
}

You should be using the indexer (i) to set the appropriate element of the string array, like so: strArray[i] = str;, but before that, you need to initialize the String array to be able to hold the number of elements you will need to store.

How do I initialize the String array if I'm going to use the input of the user?

Woops! Nevermind :D I understand everything now! Thank you so much! :D

Same way you normally would (with the new keyword), you would just use num instead of an integer value.

Now, I'm trying to create methods that use the String array. How do I pass the String array to a non-static method? Here's what I'm working on right now:

    public void printArray(String[] anArray, int numofElements){
        //accepts string array and prints out elements line by line//
    }

    public void sortList(String[] anArray, int n){
        //accepts a string array and sorts the contents in alphabetical order//
    }


    public static void main (String args[]){
    String[] strArray = new String[10];
    int num; 
    Scanner sc = new Scanner(System.in); 

    System.out.print("Enter an integer: ");
    num = sc.nextInt();

    for(int i = 0; i < num; i++){
        System.out.print("Enter String: ");
        String str = sc.next(); 
        strArray[i] = str; 
    }

    }
}

to a non static method? you want the easy approach or a decent one?
easy:
create an instance, and pass them as parameters.
more decent: make your array an instance variable, and perform all your operations on an instance, instead of in a static context.

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.