I have to store a String matrix(3x20) inside an array whose length may vary.
I am trying the following code but I am getting an incompatible types error.
How could I fix this error?
My code is:
int x=0;
String[] arrayF=new String[10];
arrayF[x]= new String[3][20];
You can't assign array this way. You should eventually assign each element of the first 2-array to the 1-d array.
Something like:
String[][] array2D =new String[M][N];
String[] array1D = new String[M * N];
for (int i = 0 ; i < M ; i++)
{
for (int j = 0 ; i < N ; i++)
{
array1D[(j * N) + i] = array2D[i][j];
}
}
arrayF is an array of strings, so each element in arrayF must be a string (by definition of the array).
What you are trying to do is is put an array (new String[3][20]), instead of a string, in each element of arrayF, which obviously contradicts it's definition (hence the incompatible types error).
One solution for what you want might be using a 3-d array of strings:
String[][][] arr = new String[10][3][20];
arrayF is one dimensional array with String type.
You cannot add two dimensional array to arrayF. For dynamic array size, you should use ArrayList.
List<String[][]> main = new ArrayList<String[][]>();
String[][] child1 = new String[3][20];
String[][] child2 = new String[3][20];
main.add(child1);
main.add(child2);
Refer to
Variable length (Dynamic) Arrays in Java
use something like this:
String [][] strArr = new String[3][20];
ArrayList<String[][]> tm = new ArrayList<String[][]>();
tm.add(strArr);
Related
My question is the same as this one except that instead of a single Document I have an array (Document[]).
I normally use R, not Java, so I apologize if it should be apparent how to change the solution from the linked thread for the case of an array.
The solution for the case of a single Document object was:
String htmlString = doc.html();
My code to create the object was:
Document[] target = new Document[20];
for(int n=0; n < strvec.length;n++){
target[n] = Jsoup.connect(strvec[n]).get();
}
I tried a few things like creating the original target object as String[], putting .toString() on the end of Jsoup.connect(strvec[n]).get() and elsewhere, but these attempts were unsucessful.
it is assumed that serves is an array of String containing the URL to connect, you do not need to create another array of Document
String[] result = new String[strvec.length];
for(int n=0; n < strvec.length;n++)
result[n]=Jsoup.connect(strvec[n]).get().html();
String[] htmlList = new String[target.length];
for(int i = 0; i < target.length; i++)
htmlList[i] = target[i].html();
This loop should do what you want.
I am trying to fill a 2D char array with 5 words. Each string must be split into single characters and fill one row of the array.
String str = "hello";
char[][] words = new char[10][5];
words[][] = str.toCharArray();
My error is at the 3rd line I don't know how to split the string "hello" into chars and fill only the 1st row of the 2-dimensional array
If you want the array to fill the first row, just asign it to the first row:
words[0] = str.toCharArray();
Since this will create a new array in the array, you should change the instantiation of words to this:
char[][] words = new char[5][];
Java has a String class. Make use of it.
Very little is known of what you want with it. But it also has a List class which I'd recommend as well. For this case, I'd recommend the ArrayList implementation.
Now onto the problem at hand, how would this code look now?
List<String> words = new ArrayList<>();
words.add("hello");
words.add("hello2");
words.add("hello3");
words.add("hello4");
words.add("hello5");
for (String s : words) {
System.out.println(s);
}
For your case if you are stuck with using arrays.
String str="hello";
char[][] words = new char[5][];
words[][] = str.toCharArray();
Use something along the line of
String str = "hello";
char[][] words = new char[5][];
words[0] = str.toCharArray();
for (int i = 0; i < 5; i++) {
System.out.println(words[i]);
}
However, why invent the wheel again? There are cases however, more can be read on the subject here.
Array versus List<T>: When to use which?
I have a String Array, map[] which looks like...
"####"
"#GB#"
"#BB#"
"####"
So map[1] = "#GB#"
How do I turn this into a 2D array so that newMap[1][1] would give me "G"?
Thanks a lot.
If you really need it, you can use String.toCharArray on each element array to convert them into an array.
String[] origArr = new String[10];
char[][] charArr = new char[10][];
for(int i = 0; i< origArr.length;i++)
charArr[i] = origArr[i].toCharArray();
If you want to break it up into String[] instead, you could use (thanks Pshemo)
String[] abc = "abc".split("(?!^)"); //-> ["a", "b", "c"]
This won't be dynamic. It will take O(n) + m to get to a character of a string. A much faster and dynamic approach would be a Hashmap where the key is the String and the value is a char array. Kind of unnecessarily complex but you get the seeking and individual letter charAts without having to go through the cumbersome process of resizing a primitive array.
I have a small issue when I run into while using arraylists in Java. Essentially I am hoping to store an array in an arraylist. I know that arraylists can hold objects, so it should be possible, but I am not sure how.
For the most part my arraylist (which is parsed from a file) is just holding one character as a string, but once in a while it has a series of characters, like this:
myarray
0 a
1 a
2 d
3 g
4 d
5 f,s,t
6 r
Most of the time the only character I would care about in the string residing at position 5 is the f but occasionally I may need to look at the s or the t as well. My solution to this is to make an array like this:
subarray
0 f
1 s
2 t
and store subarray in position 5 instead.
myarray
0 a
1 a
2 d
3 g
4 d
5 subarray[f,s,t]
6 r
I tried to do this with this code:
//for the length of the arraylist
for(int al = 0; al < myarray.size(); al++){
//check the size of the string
String value = myarray.get(al);
int strsz = value.length();
prse = value.split(dlmcma);
//if it is bigger than 1 then use a subarray
if(strsz > 1){
subarray[0] = prse[0];
subarray[1] = prse[1];
subarray[2] = prse[2];
}
//set subarray to the location of the string that was too long
//this is where it all goes horribly wrong
alt4.set(al, subarray[]);
}
This isn't working the way I would like though. It won't allow me to .set(int, array). It only allows .set(int, string). Does anyone have suggestions?
The easiest approach would be to have an ArrayList of ArrayList.
ArrayList<ArrayList<String>> alt4 = new ArrayList<ArrayList<String>>();
However, this probably isn't the best solution. You may want to rethink your data model and look for a better solution.
Just change alt4.set(al, subarray[]); to
alt4.add(subarray);
I assume alt4 is another defined ArrayList<String[]>. If not, define it as below:
List<String[]> alt4= new ArrayList<String[]>();
or
ArrayList<String[]> alt4= new ArrayList<String[]>();
My guess is that you are declaring alt4 as List<String> and that's why it is not letting you set an array of String as a list element. You should declare it as List<String[]> and is each element is only singular, simply set it as the 0th element of the String[] array before adding it to the list.
You could switch to:
List<List<Character>> alt4 = new ArrayList<List<Character>>();
May be this is what you want to get
public class Tester {
List<String> myArrays = Arrays.asList(new String[] { "a", "a", "d", "g", "d", "f,s,t", "r" });
ArrayList<ArrayList<String>> alt4 = new ArrayList<ArrayList<String>>();
private void manageArray() {
// for the length of the arraylist
ArrayList<String> subarray = new ArrayList<String>();
for(int al = 0; al < myArrays.size(); al++) {
// check the size of the string
String value = myArrays.get(al);
int strsz = value.length();
String prse[] = value.split(",");
// if it is bigger than 1 then use a subarray
if(strsz > 1) {
for(String string : prse) {
subarray.add(string);
}
}
// set subarray to the location of the string that was too long
// this is where it all goes horribly wrong
alt4.set(al, subarray);
}
}
}
I have a list of words , there are 4 words, it cant contain more that 4 its just an example. I want to use just 2 of the words the rest of them should be ignored or deleted e.g :
String planets = "Moon,Sun,Jupiter,Mars";
String[] planetsArray = planets.split(",");
int numberOfPlanets = planetsArray.length;
the result i get is 4. How do i delete the rest of the words if my list contains more that 2 words ?
As suggested in your previous question, you can use
String[] fewPlanets = new String[]{planets[0], planets[1]};
Just make sure the planets array has 2 elements or more to avoid an ArrayIndexOutOfBoundsException. You can use length to check it: if (planets.length >= 2)
For a more sophisticated solution, you could also do this using System.arrayCopy() if you're using Java 1.5 or earlier,
int numberOfElements = 2;
String[] fewPlanets = new String[2];
System.arraycopy(planets, 0, fewPlanets, 0, numberOfElements);
or Arrays.copyOf() if you're using Java 1.6 or later:
int numberOfElements = 2;
String[] fewPlanets = Arrays.copyOf(planets, numberOfElements);
String planets = "Moon,Sun,Jupiter,Mars";
String[] planetsArray = planets.split(",");
if(planetsArray .length > 2){
String []newArr = new String[2];
newArr[0]=planetsArray [0];
newArr[1]=planetsArray [2];
planetsArray = newArr ;
}
Use Arrays.asList to get a List of Strings from String[] planetsArray.
Then use the methods of the List interface -contains,remove,add, ...- to simply do whatever you want on that List.
If you need to select the first 2 planets just copy the array:
String[] newPlanetsArray = Arrays.CopyOf(planetsArray, 2);
If you need to select 2 specific planets you can apply the following algorithm:
First, create a new array with 2 elements. Then, iterate through the elements in the original array and if the current element is a match add it to the new array (keep track of the current position in the new array to add the next element).
String[] newPlanetsArray = new String[2];
for(int i = 0, int j = 0; i < planetsArray.length; i++) {
if (planetsArray[i].equals("Jupiter") || planetsArray[i].equals("Mars")) {
newPlanetsArray[j++] = planetsArray[i];
if (j > 1)
break;
}
}
You could use an idea from How to find nth occurrence of character in a string? and avoid reading the remaining values from your comma separated string input. Simply locate the second comma and substring upto there
(Of course if your code snippet is just an example and you do not have a comma separated input, then please ignore this suggestion :)