Having difficulty adding elements to 2-dimensional array - java

I have a .txt file that looks like this:
Mathematics:MTH105
Science:SCI205
Computer Science:CPS301
...
And I have an assignment that requires that I read file and place each line into an array that should look like this:
subjectsArray[][] = {
{"Mathematics", "MTH105"},
{"Science", "SCI205"},
{"Computer Science", "CPS301"}
};
I am getting a compile error when I attempt to add the contents of the file to a 2-dimensional array:
private static String[][] getFileContents(File file) {
Scanner scanner = null;
ArrayList<String[][]> subjectsArray = new ArrayList<String[][]>();
//Place the contents of the file in an array and return the array
try {
scanner = new Scanner(file);
int i = 0;
while(scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] lineSplit = line.split(":");
for(int j = 0; j < lineSplit.length; j++) {
subjectsArray[i][j].add(lineSplit[0]); //The type of the expression must be an array type but it resolved to ArrayList<String[][]>
}
i++;
}
return subjectsArray;
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
scanner.close();
}
return null;
}
Error reads:
The type of the expression must be an array type but it resolved to ArrayList<String[][]>
I am new to multi-dimensional arrays and not sure what it is I'm doing wrong. Can someone tell me what I'm doing wrong?

Your first mistake is the selection of the type for the result: this type
ArrayList<String[][]>
represents a three-dimensional structure - a list of 2D arrays. What you need is a two-dimensional structure, e.g.
ArrayList<String[]>
So the first fix is this:
List<String[]> subjectsArray = new ArrayList<String[]>(); // Note the type on the left: it's an interface
Once this is done, the rest of the code flows by itself: you do not need the inner for loop, it gets replaced by a single line:
subjectsArray.add(lineSplit);
The final fix is the return line: you need to convert the List<String[]> to String[][], which can be done by calling toArray(), like this:
return subjectsArray.toArray(new String[subjectsArray.size()][]);

I think you are trying to use an ArrayList method on a String. I am not sure that is possible. The simplest way to do what you need I think is:
for(int j = 0; j < lineSplit.length; j++) {
subjectsArray[i][j]=lineSplit[j];
}

Related

Remove elements from ArrayList after finding element with specific char

I have an ArrayList that contains a number of Strings, I want to be able to iterate through the ArrayLists contents searching for a string containing a semicolon. When the semicolon is found I then want to delete all of the Strings including and after the semicolon string.
So;
this, is, an, arra;ylist, string
Would become:
this, is, an
I feel like this is a very simple thing to do but for some reason (probably tiredness) I can't figure out how to do it.
Here's my code so far
public String[] removeComments(String[] lineComponents)
{
ArrayList<String> list = new ArrayList<String>(Arrays.asList(lineComponents));
int index = 0;
int listLength = list.size();
for(String str : list)
{
if(str.contains(";"))
{
}
index++;
}
return lineComponents;
}
This becomes trivial with Java 9:
public String[] removeComments(String[] lineComponents) {
return Arrays.stream(lineComponents)
.takeWhile(s -> !s.contains(";"))
.toArray(String[]::new);
}
We simply form a Stream<String> from your String[] lineComponents and take elements until we find a semicolon. It automatically excludes the element with the semicolon and everything after it. Finally, we collect it to a String[].
First of all I think you are confusing arrays and arraylists. String[] is an array of strings while ArrayList<String> is an arraylist of strings. Take into account that those are not the same and you should read Array and ArrayList documentation if needed.
Then, to solve your problem following the ArrayList approach you can go as follows. Probably it's not the optimum way to do it but it will work.
public List<String> removeComments(List<String> lineComponents, CharSequence finding)
{
ArrayList<String> aux = new ArrayList<String>();
for(String str : lineComponents)
{
if(str.contains(finding))
break;
else
aux.add(str);
}
return aux;
}
This example is just for performance and bringing back my old favorite arraycopy:
public String[] removeComments(String[] lineComponents) {
int index = -1;
for (int i = 0; i < lineComponents.length; i++) {
if ( lineComponents[i].contains(";") ) {
index = i;
break;
}
}
if (index == -1) return lineComponents;
return Arrays.copyOf(lineComponents, index);
}

JAVA Get each value of arraylist

I have one arraylist that contain two list
like this
[[asd, asswwde, efef rgg], [asd2223, asswwd2323e, efef343 rgg]]
My Code is
ArrayList<String> create = new ArrayList<String>();
ArrayList<String> inner = new ArrayList<String>();
ArrayList<String> inner1 = new ArrayList<String>();
inner.add("asd");
inner.add("asswwde");
inner.add("efef rgg");
inner1.add("asd2223");
inner1.add("asswwd2323e");
inner1.add("efef343 rgg");
create.add(inner.toString());
create.add(inner1.toString());
i have to get all value one by one of every index of that arraylist
So what is the best way to get these all value one by one.
I am using JAVA with Eclipse Mars.
Just use two nested loops:
List<List<Object>> list = ...;
for (List<Object> subList : list) {
for (Object o : subList) {
//work with o here
}
}
You may also want to consider replacing the inner lists by proper objects.
You want to loop through the outside ArrayList and then loop through each ArrayList within this ArrayList, you can do this by using the following:
for (int i = 0; i < outerArrayList.size(); i++)
{
for (int j = 0; j < outerArrayList.get(i).size(); j++)
{
String element = outerArrayList.get(i).get(j);
}
}
Here is another verison you may find easier to understand, but is essentially the same:
for (int i = 0; i < outerArrayList.size(); i++)
{
ArrayList<String>() innerArrayList = outerArrayList.get(i)
for (int j = 0; j < innerArrayList.size(); j++)
{
String element = innerArrayList.get(j);
}
}
or alternatively again using a foreach loop:
for (ArrayList<String> innerArrayList : outerArrayList)
{
for (String element : innerArrayList)
{
String theElement = element;
}
}
It might be worth noting that your ArrayList appears to contain different types of elements - is this definitely what you wanted to do? Also, make sure you surround your strings with "" unless they are variable names - which it doesn't appear so.
EDIT: Updated elements to type String as per your update.
I would also recommend you change the type of your create ArrayList, like below, as you know it will be storing multiple elements of type ArrayList:
ArrayList<ArrayList> create = new ArrayList<ArrayList>();
Try to use for loop nested in foreach loop like this:
for(List list : arrayListOfList)
{
for(int i= 0; i < list.size();i++){
System.out.println(list.get(i));
}
}
I'm not sure if the data structures are part of the requirements, but it would be better constructed if your outer ArrayList used ArrayList as the generic type.
ArrayList<ArrayList<String>> create = new ArrayList<ArrayList<String>>();
ArrayList<String> inner = new ArrayList<String>();
ArrayList<String> inner1 = new ArrayList<String>();
...
create.add(inner);
create.add(inner1);
Then you could print them out like this:
for(List list : create) {
for (String val : list) {
System.out.println(val);
}
}
Othewise, if you stick with your original code, when you add to the outer list you are using the toString() method on an ArrayList. This will produce a comma delimited string of values surrounded by brackets (ex. [val1, val2]). If you want to actually print out the individual values without the brackets, etc, you will have to convert the string back to an array (or list) doing something like this:
for (String valList : create) {
String[] vals = valList.substring(1, val.length() - 1).split(",");
for (String val : vals) {
System.out.println(val.trim());
}
}

Java - All Elements in List Become Identical

I'm having trouble using a for loop to assign elements to a List. Here's the section of code I'm having trouble with:
private static List<String[]> modify(List<String[]> data) {
List<String[]> data2 = new ArrayList<>();
for (int i=0; i<data.size(); i++) {
String[] block = data.get(i);
// some code here to modify the contents of block
data2.add(block);
}
return data2;
}
For some reason, this method returns a List with all its elements completely identical. I've tried outputting the List elements to see where this is happening, and it seems to be happening outside of the loop. For example, this:
private static List<String[]> modify(List<String[]> data) {
List<String[]> data2 = new ArrayList<>();
for (int i=0; i<data.size(); i++) {
String[] block = data.get(i);
// some code here to modify the contents of block
data2.add(block);
System.out.println(Arrays.toString(data2.get(i));
}
return data2;
}
displays a list of different elements, whereas this:
private static List<String[]> modify(List<String[]> data) {
List<String[]> data2 = new ArrayList<>();
for (int i=0; i<data.size(); i++) {
String[] block = data.get(i);
// some code here to modify the contents of block
data2.add(block);
}
for (int i=0; i<data2.size(); i++) {
System.out.println(Arrays.toString(data2.get(i)));
return data2;
}
displays a list consisting of only identical elements. It seems to me that the elements are being correctly added to the List inside of the for loop, yet end up becoming identical. Why is this, and how can I fix it?
You should probably make a temporary string to do the manipulations, initialize your String array, then fill it up with your data and then pass it to data2 like this:
private static List<String[]> modify(List<String> data) {
List<String[]> data2 = new ArrayList<>();
for (int i=0; i<data.size(); i++) {
String tempString = data.get(i);
String[] block = new String[255];
// some code here to modify the contents of block
// actually fill block with data
block.add("modified data");
block.add("more manipulated data");
data2.add(block);
}
return data2;
}
Edit
This should fix the no compiling problem!
It seems strange that you have managed to make this code run at all. There is an obvious syntax error in your code:
private static List<String[]> modify(List<String> data) {
...
String[] block = data.get(i);
Your block is an array of String, whereas data.get() returns a single string. In the latter of your fragments the braces are unmatched, so it also should not get compiled. If you put '}' after System.out.println(...); and made the parameter of type List<String>[] instead of List<String>, your code would work fine.

Java: printing an array without Arrays.toString

public String[] geefAlleTemplateNamen(String[][] templateLijst){
String[] lijst = new String[templateLijst.length];
for(int i = 0; i < templateLijst.length; i++){
lijst[i] = templateLijst[i][0];
}
return lijst;
}
The code above returns an array 'lijst'.
System.out.println(geefAlleTemplateNamen(templateLijst));
With this piece of code I tried to print that array, but it prints the location of the array. I know this can be solved by importing Java.util.Arrays, but I am not allowed to do this (school project), is there any way to solve this?
Thank you!
The simplest and easiest way to do this is to throw your array into a for loop.
for (int i = 0; i < lijst.length; i++) { System.out.println(lijst[i]); }
Printing the array itself should and will print its memory location, and you'll want to access each member of the array individually instead.
Easiest solution would be,
for(String s: lijst)
{
System.out.println(s);
}

how to put a list of numbers from a file into an array and return the array

In this method I am trying to create an array from a file I passed into the method (the file has a list of numbers) and then I want to return the array. But when I try to run my code the error pops up that it can't find the symbol "nums".
I'm positive I have a scope problem, but I do not know how to fix this.
How do I fix this code so that it will return the array correctly?
Here is my code:
//reads the numbers in the file and returns as an array
public static int [] listNumbers(Scanner input) {
while (input.hasNext()) {
int[] nums = new int[input.nextInt()];
}
return nums;
}
You have at least two problems here.
Firstly, nums is defined inside your while loop, and it goes out of scope when you exit the loop. This is the cause of your compilation error. You'd need to move the definition outside of your loop if you want to return it once the loop has finished.
However, there's another problem, which is that you don't know how big your array needs to be until you've read the whole file. It would be much easier to create an ArrayList<Integer> and add elements to it, and then convert this to an array (if necessary) once you've read the whole file. Or just return the list, rather than an array.
public static List<Integer> listNumbers(Scanner input) {
List<Integer> nums = new ArrayList<Integer>();
while (input.hasNext()) {
nums.add(input.nextInt());
}
return nums;
}
List<Integer> list = new ArrayList<Integer>();
while(input.hasNext())
{
list.add(input.nextInt());
}
int size = list.size();
int[] nums = new int[size];
int counter = 0;
for(Integer myInt : list)
{
nums[counter++] = myInt;
}
return nums;
This solution is not tested, but can give you some direction. It's also along the lines of what Simon is referring to as well.

Categories