0

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]);
    }
}
3
Contributors
6
Replies
20
Views
3 Years
Discussion Span
Last Post by stultuske
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.

0

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

0

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

0

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

0

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; 
    }

    }
}

Edited by laguardian

0

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.