-2

Create a function that takes an array of strings and returns an array with only the strings that have numbers in them. If there are no strings containing numbers, return an empty array.

Examples numInStr(["1a", "a", "2b", "b"]) ➞ ["1a", "2b"]

numInStr(["abc", "abc10"]) ➞ ["abc10"]

numInStr(["abc", "ab10c", "a10bc", "bcd"]) ➞ ["ab10c", "a10bc"]

numInStr(["this is a test", "test1"]) ➞ ["test1"]

This is my code

import java.util.ArrayList;
public class Challenge {
    public static String[] numInStr(String[] arr) {
        boolean addWord = false;
        ArrayList<String> output = new ArrayList<String>();
        for (String word: arr){
            for (int i =0; i<word.length(); i++){
                if (Character.isDigit(word.charAt(i))){
                    addWord = true;
                }
        }
        if (addWord) {
                        output.add(word);
                        addWord=false;
        }
        return output;
    }
    }
}

What is wrong?

Also why do I have to set a type for arraylist? Whenever I do, it says its unsafe. How would I do an arraylist that contains multiple datatypes?

Tony
  • 387
  • 1
  • 2
  • 14
  • 2
    Reading the instructions: are you trying to return an ArrayList or an array? As these are two [different data structures](https://www.codementor.io/@amitrai/difference-between-array-and-arraylist-ouqlh7kpp). – LinkBerest Nov 14 '20 at 23:10
  • 4
    Does this answer your question? [Converting 'ArrayList to 'String\[\]' in Java](https://stackoverflow.com/questions/4042434/converting-arrayliststring-to-string-in-java) – Hamed Nov 14 '20 at 23:12
  • Your code has another problem. Your `return` statement is in the wrong place. I guess your compiler should tell you about it once you fix the return type problem. – CryptoFool Nov 14 '20 at 23:36
  • Always search Stack Overflow thoroughly before posting. – Basil Bourque Nov 15 '20 at 01:44
  • As you learn programming, you will realize that there are very few times that you will want to have multiple types in one list. You can do it, but it's almost always a mistake. – NomadMaker Nov 15 '20 at 01:44

4 Answers4

2

You can't return a different datatype, ArrayLists and Arrays are different types. Use

return output.toArray(new String[0]);

to convert the list to an array first

1

String[] and ArrayList<String> are different types. You have to change declaration of your method or convert ArrayList to array before returning:

    return output.toArray(new String[0]);

Also why do I have to set a type for arraylist?

ArrayList should declare the type of its elements. For list with any elements use:

ArrayList<Object>
Piotr Praszmo
  • 17,928
  • 1
  • 57
  • 65
  • why do I have to include the new String[0] in the brackets? – Tony Nov 14 '20 at 23:17
  • I understand that it is to create a new string array but [0] doesn't that set the size to zero? and you cant change array sizes no? – Tony Nov 14 '20 at 23:22
  • 1
    That `String[0]` is being passed in just to define the type of array you want to create. The reason this is necessary has to do with the fact that arrays have a specific type at runtime, but an `ArrayList` does not. Type erasure removes all generic type information from the code. So at runtime, the code can't know what type of array to create unless it has another array to get the type from. You can also pass in an array that is large enough to hold the result, and the code will then just use that array. – CryptoFool Nov 14 '20 at 23:42
0

The return value must match with the return type. Since you have declared the return type as String[], you must return a String[] which you can do by returning output.toArray(new String[0]).

Apart from this, you can solve the problem using Java Regex API in a much simpler and cleaner way:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        // Test
        String[] arr = { "1a", "a", "2b", "b" };
        System.out.println(Arrays.toString(numInStr(arr)));
    }

    public static String[] numInStr(String[] arr) {
        Pattern pattern = Pattern.compile("\\d+");// One or more digits
        List<String> output = new ArrayList<>();
        for (String s : arr) {
            if (pattern.matcher(s).find()) {
                output.add(s);
            }
        }
        return output.toArray(new String[0]);
    }
}

Output:

[1a, 2b]
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
-2

import java.util.*;

public class ArrayListTOArray { public static void main(String[] args) {

    /*ArrayList declaration and initialization*/
    ArrayList<String> arrlist= new ArrayList<String>();
    arrlist.add("String1");
    arrlist.add("String2");
    arrlist.add("String3");
    arrlist.add("String4");

    /*ArrayList to Array Conversion */
    String array[] = new String[arrlist.size()];              
    for(int j =0;j<arrlist.size();j++){
      array[j] = arrlist.get(j);
    }

    /*Displaying Array elements*/
    for(String k: array)
    {
        System.out.println(k);
    }
}

}

  • 2
    Your answer is 1) late (question already answered), 2) a code-only answer (frowned upon), 3) doing something the hard way that can be done in 1 line of library code, 4) not formatted correctly, and 5) does not answer the question. – CryptoFool Nov 14 '20 at 23:41