简体   繁体   中英

How to define a string array without length in java?

I'm confused about a simple question. Can you tell me how to define a string array without length? Because I can't find any information about this question. if I write String[] str=new String[]; or String[] str=new String[]{}; they will have error. But why? Thx!!!

Here is my homework: write a program to read a series of words from the command-line arguments, and find the index of the first match of a given word. For example,java First Match lady That young lady looks after the old lady. would find the index for the first match of “lady” in the sentence “That young lady looks after the old lady”, and display the index of its first occurrence in the sentence on console, eg,“The index of the first match of 'lady'is 2”.

Here is my code:

String[] str=new String[11];
        int a=0;
        for(int i=0;i<11;i++){
            str[i] = args[a];
            a++;
        }

In your case, you can count the number of args as follows:

int argsCount = args.length;

You can then create you array as follows:

String [] str = new String[argsCount - 1];

You can then fill the strings array with the words and search the array to find the first argument passed to your programs

If you must use an array that can be resized, you should use LinkedList https://www.tutorialspoint.com/java/java_linkedlist_class.htm

Arrays are fixed length data structures in Java. When you instantiate it you must either define size of array for example:

String [] myString = new String [5];

Or you should instantiate it with its members.

String []myStringArray = new String []{"first","second"};

If you do not know how many elements you will get, use ArrayList instead. Size of an ArrayList can increase or decrease at runtime dynamically. You can look at this question for more information about ArrayLists.

Requirements:

  • First command line argument is the word to search for
  • Other arguments is a space separated list forming a sentence
  • Program should return the index of the first argument in the other arguments

Sample implementation:

public static void main(String[] args)
{
    // Check whether min. one argument is provided.
    if (args.length == 0)
    {
        System.err.println("No arguments provided");
        System.err.println("Usage: <match> <word1> <word2> [...]");
        return;
    }

    // First argument is the word to search for.
    String match = args[0];

    // Iterate the other arguments to find a match.
    for (int i = 1; i < args.length; i++)
    {
        if (match.equals(args[i]))
        {
            // The first argument is the word to search for: Substract index by 1.
            System.out.printf("The index of the first match of '%s' is %d\n", match, (i - 1));
            return;
        }
    }

    System.out.printf("No match of '%s' found\n", match);
}

You should specify the length of an array when you allocate memory for it , but this is not required when you declare it. The reason is that JVM should know how much memory should be allocted before allocating memory for the array.

So I think ecen though you can declare an array without length, but you can't actually use the array before you specify the amount of memory that you need.

To solve this problem, people developed ArrayList . ArrayList does not require the size of the array. All you have to do is:

ArrayList<String> array=new ArrayList<String>();
for(int i=0;i<args.length;++i)
{
    array.add(args[i]);
}

To convert the ArrayList to String[] array, use this.

String [] arrarray=new String[array.size()];
arrarray=array.toArray(arrarray);

If you want a String[] with 0 length:

String[] test = new String[0];

And then

System.out.println(test.length);

will give you

0

EDIT

The asker's question was "how to define a string array without length in Java.

To answer the asker's entire problem, "write a program that reads a series of words from the command line and find the index of the first match of a given word", two simple methods are needed.

One method to read in the argments, and another method to find the appropriate index.

If the asker is using the String[] args of the main method for this, the problem is reduced to just one method (finding the index of the word they're looking for).

for example

public static int findIndex(String term, String[] args) {
    int index = -1;

    for (int i = 0; i < args.length; i++) {
        if (args[i].equals(term)) {
            index = i;
            break;
        }
    }

    return index;
}

and therefore, if the asker has a list of words that come in from the main method,

findIndex("lady", args);

will return the index.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM