Write a method that will search an array of strings for all strings that contain another string, ignoring capitalization. Then return an array of the found strings.
The method takes two parameters, the query string and the array of strings to search, and returns an array.
If the string isn't contained in any of the strings in the array, the method returns an array containing a single string: "Empty".
Example: If the string to search for is "me", and the array to search is ["home", "milk", "Mercury", "fish"], the method should return ["home", "Mercury"].
That's my solution and it works in Eclipse, but in a game they display an error message:
array lengths differed, expected.length=1 actual.length=0
Code:
static String[] findWord(String x, String[] y){
ArrayList<String> arrList = new ArrayList<String>();
for(String s: y){
if(s.toLowerCase().contains(x.toLowerCase()))
arrList.add(s);
}
String[] arr = arrList.toArray(new String[arrList.size()]);
if(!arrList.isEmpty())
return arr;
else
return new String[0];
}
I don't know what it means, I try to find it on Google but i can't find something useful for me.
array lengths differed, expected.length=1 actual.length=0
This means you're returning an array of length 0 when the correct return value is an array of length 1. The expected length is 1, and the length you actually returned is 0.
When do you return an array of length 0? It must be the last line of your function that's at fault since that's the only place you return an empty array.
Your code is failing this condition:
If the string isn't contained in any of the strings in the array, the method returns an array containing a single string: "Empty".
When there's no match you're returning new String[0]. You need to return a 1-element array containing the string "Empty".
Related
Curious why declaring an empty array of non-emtpy array(s) is legal in Java:
int[][] array = new int[0][1];
System.out.println(array[][0]); //won't compile.
System.out.println(array[0][0]) //triggers an out of bounds exception.
P.S. I have read the related question on zero-size arrays: Why does Java allow arrays of size 0?
Is this for the same reason?
An int[][] array is an array whose elements are int[] (i.e. its elements are arrays of int).
Just like you are allowed to define an empty array of int elements:
int[] empty = new int[0];
or an empty array of String elements:
String[] empty = new String[0];
You are also allowed to define an empty array of int[1] elements:
int[][] empty = new int[0][1];
Perhaps it's the syntax that is somewhat confusing here.
If it was
int[][] empty = new (int[1])[0]
it would be clearer that you are defining an empty array whose element type is int[1].
However, since the number in the first square brackets represents the number of elements in the outer array, new int[1][0] does not represent an empty array, but an array of a single element (whose single element is an empty int array).
It is legal to define empty arrays in general, no matter what it contains. Thus, it is also legal to have an empty array containing non empty arrays.
Mathematically (group theory) speaking, empty arrays are not only legal, but necessary, since they represent the zero (or neutral) element of array concatenation operation. This also makes it useful for programming (see the example below).
In your example you basically probe, if it is ok to access elements of an empty array. This is of course not legal, since there are none. However you can do:
int[][] array = new int[0][1];
System.out.println(array.length);
With reference to my own example above, a more useful case is:
int[][] array1 = new int[1][1];
int[][] array2 = new int[0][1];
array1[0][0] = 1;
int [][] concat = Stream
.concat(Arrays.stream(array1), Arrays.stream(array2))
.toArray(int[][]::new);
System.out.println(Arrays.deepToString(concat));
Thus empty arrays allow to for "good" code, without ifs to exclude, illegal cases, which actually are totally fine.
as per your declaration:
int[][] array = new int[0][1];
you have declared 2D array where length of the array is 0
it means it will not be able to contain any element thats why
System.out.println(array[0][0]). array[0][0] is out of bound index error
An array dimension of zero means the array has zero elements. Hence there is no element at index 0 (zero).
When you declare a two-dimensional array in Java, the first array dimension is mandatory.
Refer to chapter 10 of the Java Language Specification.
I have a code
String ejgStr[] = new String[][]{{null},new String[]{"a","b","c"},{new String()}}[0] ;
System.out.println(ejgStr[0]);
which compiles without error.
From what I understand you can't create an array with non-matching square brackets.
On the left, we have String ejgStr[], which is 1-d array and
On the right, we have String[][]{some array}[0], which is 2-d array
These seem to have different dimensions but why do they successfully compile?
You are assigning a one-dimensional String[] array to the first dimension of an inline two-dimensional String[][] array. Have a look the comments:
String ejgStr[] =
new String[][] {
{ null }, // a null 1D String array
new String[] {"a","b","c"}, // a 1D String array containing a,b,c
{ new String() } // a String array containing empty String
}[0]; // access the { null } 1D array
I expect your assignment to be equivalent to doing this:
String ejgStr[] = { null };
You assign a 1D array to the ejgStr refference. If you look at the end of the first statemend, you will see that you have a [0] index specified which means you will assign the first array (position 0) to your referrence. If you remove the [0] you will receive a compilation error.
new String[][]{...} is a 2D array.
new String[][]{...}[0] is the first element of a 2D array, which is a 1D array.
That's what you're assigning to String ejgStr[].
String ejgStr[] is just a reference to a variable in heap space.
you're pointing to first dimensional of 2D-dimensional array using [0] and make a reference of it in ejgStr[]. this is not common to get 1D from 2D array, but you can do it if you need and of course it wont make compile error.
return getRights(obj, attrs)[0];
What is the meaning of the [0] in the above return statement?
getRights(...) returns an array, and you're returning the first item in that array from your method. Note that Java arrays are 0 based, and so the first index of any array will be [0]. This method could potentially run into trouble if the array returned by getRights(...) is empty and has no elements or if getRights(...) could possibly return a null value.
It means the same as...
array[] = getRights(obj, attrs);
return array[0];
..., which just returns the first element in the array.
I am looking to print out my original unsorted array, I have it printing in order and sorted but I can't seem to get the original one to print out unsorted. I have used printRuleAndArray(String rule) and I have also used LengthCompare for the new sorted array, my problem is the original!!!
import java.util.*;
import java.util.Arrays;
// Example of how to sort an array
public class Sorting2
{
//declare an array of strings
static String[] nameArray = {"Alan", "Peter", "Ed", "Stephen", "Pheadraa"};
public static void main(String[] args)
{
// sorting by length
Arrays.sort(nameArray, new LengthCompare());
//print out elements of array
System.out.println(Arrays.toString(nameArray));
//count the number of elements in the array
int counter=nameArray.length;
//print out numeric number of elements in array
System.out.println("Number of elements in array: " + counter);
//print out sorted array with shortest first and longest last
printRuleAndArray("Sorted list by name length:");
}
Arrays.sort() will always sort the array you pass into it, it doesn't produce a fresh copy - so if you really need the unsorted array to hang around as well as the sorted array, then you'll have to make a copy of it:
String copyArr[] = new String[nameArray.length];
System.arraycopy( nameArray, 0, copyArr, 0, nameArray.length );
However, preferable to this approach (if feasible) would just be to do all the operations you need on the unsorted array (such as printing it or converting it to a string), then sort it afterwards.
As pointed out in the comment, Arrays.copyOf() could also be used to accomplish the same thing.
Arrays.sort will have altered your original array. Your choices are to either print your original array before sorting it, or to copy your original array and sort the copy.
Call String unsortedArr = Arrays.toString(nameArray); before array sorting, and when you need to print unsorted array just call System.out.println(unsortedArr);
Arrays.sort() sorts the array you pass into it. If you would like the original array later, copy the array first and then sort that array.
for(String arr : nameArray ) { //arr gets successively each value in nameArray.
System.out.println(arr);
}
this example is using foreach loop
Do something like this
String orig = Arrays.toString(nameArray);
Arrays.sort(nameArray, new LengthCompare());
String sorted = Arrays.toString(nameArray);
System.out.println(orig);
System.out.println(sorted);
Let me give you an example;
String[] one = {"one", "two"};
String[] two = {"bob", "lol", "hi"};
List<String[]> list = new ArrayList<String[]>();
list.add(one);
list.add(two);
Now, I want to get the 2nd string array (which is 'two') in list. I do this by:
list.get(2);
But, say if I wanted to get the 2nd element in the two String array in List ( Basically I want to get the string "lol" from list->two->lol).
Is this how you do it:
list.get(2).get(2)
Indices in Java (and in most programming languages) starts with 0, so if you want to access to the second element you must use the index 1:
list.get(0)[1];
Note that
list.get(0)
will return the first String[] array, and to access to an element of an array you have to use the syntax:
someArray[index]
Array starts with index 0. so you have to use list.get(i)[1]