I'm using Eclipse and I'm trying to take a string:
1 2 3 4
out of an ArrayList:
ArrayList strings = new ArrayList<>();
And store each number into a two dimensional array:
int size = (int) strings.get(0); // Represents the number of rows
int stringList[][] = new int[size][];
// Store results in a two dimensional array
for(int i = 0; i < size; i++){
int index = i + 1;
String fish = (String) strings.get(index);
Scanner npt = new Scanner(fish);
for(int j = 0; npt.hasNext(); j++) {
size[i][j] = Integer.parseInt(npt.next());
}
}
This is the section that is causing the error:
// ERROR: The type of the expression must be an array type but it resolved to int
size[i][j] = Integer.parseInt(npt.next());
strings is a raw type. Let's start by fixing that1,
List<String> strings = new ArrayList<>();
Then you can use Integer.parseInt(String) parse2 the String to an int like
int size = Intger.parseInt(strings.get(0));
Then there's no need for a cast in
String fish = (String) strings.get(index);
You can use
String fish = strings.get(index);
etc.
1 And program to the List interface.
2 Not cast.
You probably meant
stringList[i][j] = Integer.parseInt(npt.next());
though that wouldn't work either, unless you properly initialize the stringList array.
You would have to initialize stringList[i] (for each i) with something like stringList[i] = new String[someLength]; but I'm not sure which length you should use.
Related
This question already has answers here:
How can I concatenate two arrays in Java?
(66 answers)
Closed 5 years ago.
I have 2 String variables,
String expectedDocsTextReqA = "A1:A2:A3:A4";
String expectedDocsTextReqB = "B1:B2:B3:B4";
And I want to Split these 2 strings and store it in a single String array How to do that?
I'm trying to achieve something like this, But this will throw an exception. Is there any alternate way to do this?
String[] arr = expectedDocsTextReqA.split(":") + expectedDocsTextReqB.split(":");
When you use Split method, this creates an array of strings which cannot be resized. The solution is to convert your array of strings into a list of strings:
String expectedDocsTextReqA = "A1:A2:A3:A4";
String expectedDocsTextReqB = "B1:B2:B3:B4";
List<String> list = new ArrayList<String>();
list.addAll(Arrays.asList(expectedDocsTextReqA.split(":")));
list.addAll(Arrays.asList(expectedDocsTextReqB.split(":")));
for (int i = 0; i < list.size(); i++)
System.out.println(list.get(i));
Probably not the most efficient way to do something like this, but here goes.
String[] split1 = expectedDocsTextReqA.split(":");
String[] split2 = expectedDocsTextReqB.split(":");
//initialize result array size.
String[] result = new String[split1.length + split2.length];
int index = 0;
for (int i = 0; i < split1.length; i++) { //add elements of the first array
result[index] = split1[i]
index++;
}
for (int i = 0; i < split2.length; i++) { //add elements of the second array
result[index] = split2[i]
index++;
}
edit: The List implementation by Joris is probably a more reasonable method of going about this problem.
List<String> list2 =new ArrayList<String>();
int iArr[] = new int[ja.length()];//{"846001","846005","846000","846002","846009"}
Arrays.sort(iArr);
for (int i = 0; i < ja.length(); i++) {
_jobject = ja.getJSONObject(i);
iArr[i] = Integer.parseInt(_jobject.getString("Pincode"));
}
for(int k=0;k<iArr.length;k++) {
list2.add(String.valueOf(iArr[k]));
}
I want to sort and bind it in Array list. I want
{"846000", "846001", "846002" ,"846005", "846009"}
but its not sorting according to given logic please suggest me where am doing wrong.
I think the issue is that you are sorting the array before manipulating it. You should move Arrays.sort(iArr) to after the for loop.
List<String> list2 =new ArrayList<String>();
int iArr[] = new int[ja.length()];//{"846001","846005","846000","846002","846009"}
for (int i = 0; i < ja.length(); i++) {
_jobject = ja.getJSONObject(i);
iArr[i] = Integer.parseInt(_jobject.getString("Pincode"));
}
Arrays.sort(iArr);
for(int k=0;k<iArr.length;k++) {
list2.add(String.valueOf(iArr[k]));
}
The values are accessed as String so convert it to Integers and then sort it. As of now you are sorting it before you populate it properly.
for (int i = 0; i < ja.length(); i++) {
_jobject = ja.getJSONObject(i);
iArr[i] = Integer.parseInt(_jobject.getString("Pincode"));
}
Arrays.sort(iArr);
for(int k=0;k<iArr.length;k++) {
list2.add(String.valueOf(iArr[k]));
}
Let's simulate how your given logic will be executed when it comes to the processor.
Line 1: initialized an empty string type ArrayList
Line 2: initialized an empty int array, with the length of ja.length() long
Line 3: you sort the empty int array
Line 4 to line 7: assign Pincode to your int array sequentially from the json
We have no idea what those json object stored, but apparently they are not sorted. When they get copied to your int array, the int are not sorted as well.
Move line 3 after the line 4 to 7 for loop should do the job. You should sort the array when there is some element inside. Sort an empty has no effect.
I've read data from a text file and stored them in an array called 'boat1'.
There are nine values and I am trying to add together index's [4] to [9] to get a total value.
How would I go about doing this?
Here is my code:
String[] boat1 = new String[9];
int i = 0;
while(reader.hasNextLine() && i < boat1.length) {
boat1[i] = reader.nextLine();
i++;
}
I've tried to change the values to an integer but it doesn't seem to be working..?
Thank you.
You got to parse before adding:
int a = Integer.parseInt(boat1[3]);
int b = Integer.parseInt(boat1[8]);
int c = a + b;
Your array boat1 is a String array and not an int array. You need to convert it. Note that boat1 is size of 9 meaning that it has indexes from 0 to 8. Java is 0 based.
If you want to add up a sequence of numbers (ex. 3,4,...,7,8), just loop through the indexes you want to add up and keep track of a total.
Because your array is an String type it needs to be converted to int, After you do that you will have something like this example assuming that I'm making up those values , but it should still work for your code :). Don't forget to add the for loop at the end as I have it on my code so it can find the sum of your indexes. Hope it can help you!
int sum = 0;
int[] boat = new int[9];
boat[0] = 2;
boat[1] = 4;
boat[2] = 6;
boat[3] = 8;
boat[4] = 10;
boat[5] = 12;
boat[6] = 14;
boat[7] = 16;
boat[8] = 18;
for(int i = 3; i < boat.length ; i++){
sum += boat[i];
}
System.out.println(sum);
Just to keep my skills sharp, I decided to write a small programme that prints out the values of an array, after being given two variables that each contain a different value.
My expectation was that each value would show onscreen, but this did not happen. Instead, only the last element's value was displayed onscreen (in the code below, being the number "2" --> That is an integer, not a string).
Why is this?
Also, why does dynamic initialisation produce the result I wish, but not the way I do it in the code?
Many thanks.
int[] arrayOne;
arrayOne = new int[2];
int numOne = 1;`
int numTwo = 2;`
for (int i = 0; i < arrayOne.length; i++) {`
arrayOne[i] = numOne;
arrayOne[i] = numTwo;
System.out.println(arrayOne[i]);
}
If you want to put the values of two variables into an array, you need to use two assignments:
arrayOne[0] = numOne;
arrayTwo[1] = numTwo;
Now you can use a for loop to print out the contents of the array.
This kind of defeats the purpose of using an array, though.
You're setting different values to same location, causing only last value to be saved.
Your code similar to doing:
arrayOne[0] = 1;
arrayOne[0] = 2;
After these two lines, arrayOne[0] will hold the value of 2.
If you want to put these two values, you need to put them in different places:
arrayOne[0] = 1;
arrayOne[1] = 2;
In Java (and in almost any language I know), an array can only contain one vale per cell i.e. if you do "array[i] = 1" and after "array[i] = 2" , then the i-cell will CHANGE its value from 1 to 2, not append the value 2 after the 1. In the end, youre array will contain numTwo in every single cell.
If you want to initialize the array with a different value in each cell, I'm afraid you need to do it manually, not using the loop.
You need to do the population of your array before you iterate through it with the loop.
arrayOne[0] = numOne;
arrayOne[1] = numTwo;
Then do your loop:
for (int i = 0; i < arrayOne.length; i++)
{
System.out.println(arrayOne[i]);
}
Many ways to initialize an array...
int[] a = new int[2];
a[0] = 1;
a[1] = 2;
Or:
int[] a = new int[2];
for( int i = 0; i < a.length; i++ ){
a[i] = i + 1;
}
Or:
int[] a = new int[]{ 1, 2 };
Or.
int valOne = 1;
int valTwo = 2;
int[] a = new int[]{ valOne, valTwo };
Take care when you see more than one assignment to the same array element in a loop as you have it before the println. Is this what you want? The second one wins and sets the current (i-th) element to 2.
You need to do something like this:
public class demo{
private static int i = 0;
private static int[] demo = new int[10];
public static void main(String[] args){
for(int i = 0; i < 10; i++){
addElementToArray(i);
}
for(int i = 0; i < demo.length; i++){
System.out.println(demo[i]);
}
addElementToArray(i);
}
public static void addElementToArray(int input){
try{
demo[i] = input;
i++;
}catch(ArrayIndexOutOfBoundsException e){
e.printStackTrace();
}
}
}
Don't set the values inside the for-loop either, that is (imo) plain stupid, for what you are trying to achieve
I'm writing a program to multiply matrices (2d arrays) as efficiently as possible, and for this i need to split my two arrays into two each and send them off to a second program to be multiplied. The issue I have is how to split a 2d array into two 2d arrays, at specific points (halfway). Does anyone have any ideas?
Lets say you have a 2d array of strings like so
String[][] array= new String[][]
{
{"a","b","c"},
{"d","e","f"},
{"h","i","j"},
{"k","l","m"}
};
Now you need a way to split these arrays at the half way point. Lets get the halfway point. Figure out how big the array is and then cut it in half. Note that you also must handle if the array is not an even length. Example, length of 3. If this is the case, we will use the Math.floor() function.
int arrayLength = array.length;
int halfWayPoint = Math.floor(arrayLength/2);
//we also need to know howmany elements are in the array
int numberOfElementsInArray = array[0].length;
Now we have all the info we need to create two 2d arrays from one. Now we must explicitly copy create and copy the data over.
//the length of the first array will be the half way point which we already have
String [][] newArrayA = new String[halfWayPoint][numberOfElementsInArray];
//this copies the data over
for(int i = 0; i < halfWayPoint; i++)
{
newArrayA[i] = array[i];
}
//now create the other array
int newArrayBLength = array.length - halfWayPoint;
String[][] newArrayB = new String[newArrayBLength][numberOfElementsInArray];
/*
* This copies the data over. Notice that the for loop starts a halfWayPoint.
* This is because this is where we left of copying in the first array.
*/
for(int i = halfWayPoint; i < array.length; i++)
{
newArrayB[i] = array[i];
}
And your done!
Now if you want to do it a little nicer, you could do it like this
int half = Math.floor(array/2);
int numberOfElementsInArray = array[0].length;
String [][] A = new String[half][numberOfElementsInArray];
String [][] B = new String[array.length - half][numberOfElementsInArray];
for(int i = 0; i < array.length; i++)
{
if(i < half)
{
A[i] = array[i];
}
else
{
B[i] = array[i];
}
}
And lastly, if you dont want to do it explicitly, you can use the built in functions. System.arraycopy() is one example. Here is a link to its api System.arraycopy()
int half = Math.floor(array/2);
int numberOfElementsInArray = array[0].length;
String [][] A = new String[half][numberOfElementsInArray];
String [][] B = new String[array.length - half][numberOfElementsInArray];
System.arraycopy(array,0,A,0,half);
System.arraycopy(array,half,B,0,array.length - half);