How to assign a string variable value to a 2d array - java

I am trying to populate a 2d array with String values.
int m; n; are used in my loops to assign to rows and columns.
In an inner loop I am pulling out strings from a separate string array and assigning each value to a string variable. Then I am trying to assign that string variable to the 2d array of strings.
String variable = value of string in string array at a specific index;
String[m][n] example = variable;
It seems to working fine except it doesn't seem to be loading the string in the string variable into the 2d array.
Can anyone help me to understand why this is happening and how I might successfully assign the data to the 2d array?
for(m = 0; m < people.size(); m++){
for(n = 0; n < people.get(m).getNames().length; n++){
for(int i = 0; i < people.size(); i ++){
for(j = 0; j < people.get(i).getNames().length; j++){
String name = people.get(i).getNames()[j];
}
NamesGrid [m][n] = name;
}

It's hard to tell just what you want to accomplish. The fact that you've posted non-matching curly braces doesn't help.
But basically, a double to populate all the array elements would look like:
for(m = 0; m < people.size(); m++){
for(n = 0; n < people.get(m).getNames().length; n++){
namesGrid[m][n] = ?????????;
}
}
where you have to fill in the expression. (And maybe add some code above the assignment to help with the computation.)
So what info do we have at the point where the array element is being assigned? We know what m and n are--the row and column of the namesGrid array. It also looks like they are also the "row" and "column" of objects in some people object. (It looks like people has several lists of names, and people.get(i) gives you one list of names? I'm not sure.)
But since we already know the row and column numbers for people, i.e. m and n, we can use those to access the data in people. We don't need extra for loops to do that. Or, to look at it another way: you need to iterate through all the elements of namesGrid, and you need to iterate through all the people, but you are iterating over them at the same time since the two structures are roughly the same shape, so to speak. When you use m and n to iterate through namesGrid, they are also iterating through people. So you don't need extra loops to iterate through people.
So get rid of those two extra i and j loops, and just use m and n to get the name:
String name = people.get(m).getNames()[n];
If this isn't what you really wanted, please edit your question and provide more details. Also, variable names by convention begin with a lower-case letter in Java, so I've changed namesGrid in my answer.

Try going through the 2d array using two for loops. Here is some sample code that goes through a for loop and assigns every element with a string.
String[][] names = new String[14][10];
for(int rows = 0; rows < names.length; rows++) {
for(int cols = 0; cols < names[0].length; cols++) {
names[rows][cols] = "Strings!";
}
}
for(int rows = 0; rows < names.length; rows++) {
for(int cols = 0; cols < names[0].length; cols++) {
System.out.print(names[rows][cols]);
}
System.out.println();
}

Related

I cannot get the final column in a 2D array to print

My task is to take the original 2D array, and calculate the weight of each index and create a new array with the new values. I just can't output the final column of the new array
Thank you!
Your loops should look like this:
for (int i = 0; i < calcWeight.length; i++) {
// note the calcWeight[i], you´ll get the first dimension length
// if you leave out the [i] part
// This way your inner loop would stop at 4 (rather 5 because <=)
// instead of its actuall length, 6
for (int j = 0; j < calcWeight[i].length; j++) {
...
}
}

Filling 2d array

Okay probably it's a very easy solution, but I can't seem to find it. I've got two ArrayLists:
ArrayList<Candidate>partyList and ArrayList<Party>electoralList
Now I want to make a 2d int array that represents the parties and candidates like this:
p c
1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3
etc.
I think I already have the right for-loop to fill the array but I only miss the correct formula to do it.
int[][]ArrList;
for (int i=0; i<parties.size(); i++){
for(int j=0; j<parties.get(i).getPartyList().size(); j++){
ArrList[i][j]=
Is the for-loop indeed correct? And what is the formula to fill the array then?
I will try and answer the question from how I understood what you are looking for here.
You should understand this first:
A 2D array consists of a nestled array i.e. ArrList[2][3] = [ [1,2,3], [1,2,3] ] -> The first digit declares How many arrays as elements, the second digit declares Size or if you like: length, of the array elements
If you are looking for to represent the candidates and parties as numbers. Here is my solution:
int[][]ArrList = new int[parties.size()][electoral.size()]
for (int depth=0; depth < parties.size(); depth++){
for(int itemIndex=0; itemIndex<parties.get(depth).getPartyList().size(); itemIndex++){
ArrList[depth][itemIndex]= itemIndex;
I hope this is what you were looking for.
First of all, ArrList should not have a starting capital letter (it is not a class but an object).
Second point (I think what troubles you) is that you are not initializing the matrix and the parties.size() are always 0. I am not sure since there is not enough code though.
You could do something like this
int ROWS = 10;
int COLS = 2;
int [][] matrix = new int[ROWS][];
for(int i=0; i< matrix.length; i++){
matrix[i] = new int[COLS];
}
or, with lists
int ROWS = 10;
int COLS = 2;
List<List<Object>> matrix = new ArrayList<>(ROWS);
for (int i = 0; i < ROWS; i++) {
ArrayList<Object> row = new ArrayList<>(COLS);
for (int j = 0; j < COLS; j++) {
row.add(new Object());
}
matrix.add(row);
}
int[][] arrList=new int[parties.size()][2];
int i=0,j=0,k=0;
for(;i<parties.size();i++,j++){
if(j==1){
arrList[k][j]=electoralList .get(--i);
j=-1;
k++;
}
else{
arrList[k][j]=parties.get(i);
}
}
arrList[k][j]=aarM.get(electoralList .size()-1);
System.out.println(Arrays.deepToString(arrList));

how to iterate on array[...][i] (columns) in java

There is a really easy way to access the rows of a 2D array in java
for (int i = 0 ; i < integer2D.length ; i++)
getMyArray(integer2D[i]);
But, I searched in the web to find such easy way to iterate on columns of the 2D-array, like
for (int j = 0 ; j < integer2D[0].length ; j++)
getMyArray(integer2D[][i]);
or
for (int j = 0 ; j < integer2D[0].length ; j++)
getMyArray(integer2D[...][i]);
which works in some programming languages. I just found the class RealMatrix and MatrixUtils that I can convert my array2D to a real matrix and then transpose it and again convert it to an array and iterate on it. But I suppose that there exist a simpler way?
Edit: iterating on rows as I noted in the first piece of code is easy but the main question is how to iterate on columns like the second and third codes work in some other programming languages.
Edit2: As I mentioned in the last paragraph of the main question, the easiest way that I know is transposing the matrix and the iterating on its rows.
If I understand your question, you could use a for-each as an easy way to get each row like
for (int[] row : integer2D) { // <-- for each int[] in the int[][]
for (int val : row) { // <-- for each int in the int[] row
// ...
}
}
For this, you can use the BigMatrixImpl Class of the commons math library. It has a getColumnAsDoubleArray() method which will return the specified column as an array.
Delivering only one index will give you the whole row, so:
integer2D[5] // returns an int[]
will give you an integer array, which is the 6th row in your matrix.
If you supply both indexes directly you get the value of the "cell"
integer2D[5][1] // returns an int
will give you the value of the second column of the 6th row.
This is direct access to your matrix, if you want to iterate through the rows the answer from Elliott is what you are looking for.
Edit: Transposing:
int width = array.length;
int height = array[0].length;
int[][] array_new = new int[height][width];
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
array_new[y][x] = array[x][y];
}
}

Java cannot find symbol for loops, logic problems?

Ok, my program in this specific section takes a line of data from a studentAnswer string array, the value of which would be something like TTFFTFTFTF. I am supposed to take this, and compare it against a key array, which might look like TFFFTFTFTF. A student takes a quiz, and my program calculates the points correct.
My intention is to use a separate points array to find the numeric grade for the student. The index of studentAnswer refers to a specific student. So studentAnswer[i] is TTFFTFTFTF. I use substrings to compare each individual T/F against the correct answer in key[], which would have a single T/F in each index. Then, if they are correct in their answer, I add a 1 to the correlating index in points[] and will later find the sum of points[] to find the numeric grade out of ten.
My problem here is that String origAns, used to define the student's original answer string, is getting a Java Error cannot find Symbol. I have tried placing the instantiation of origAns within each different for loop, but I can't get the program to work. Int i is meant to follow each specific student- I have four parallel arrays that will all log the student's ID number, numeric grade, letter grade, and original answers. So that is the intention of i, to go through each student. Then j should be used to go through each of these original student answer strings and compare it to the correct answer...
Logically, it makes sense to me where I would put it, but java doesn't agree. Please help me to understand this error!
for (int i = 0; i < studentAnswer.length; i++){
String origAns = studentAnswer[i];
for (int j = 0; j < key.length; j++){
if (origAns.substring[j] == key[j]){
//substring of index checked against same index of key
points[j] = 1;
}
if (origAns.substring[j] != key[j]){
points[j] = 0;
}
}
}
It sounds like you're trying to call the substring method - but you're trying to access it as if it were a field. So first change would be:
if (origAns.substring(j) == key[j])
Except that will be comparing string references instead of contents, so you might want:
if (origAns.substring(j).equals(key[j]))
Actually, I suspect you want charAt to get a single character - substring will return you a string with everything after the specified index:
if (origAns.charAt(j) == key[j])
... where key would be a char[] here.
You can also avoid doing the "opposite" comparison by using an else clause instead.
You should also indent your code more carefully, for readability. For example:
for (int i = 0; i < studentAnswer.length; i++) {
String origAns = studentAnswer[i];
for (int j = 0; j < key.length; j++) {
if (origAns.charAt(j) == key[j]) {
points[j] = 1;
} else {
points[j] = 0;
}
}
}
And now, you can change that to use a conditional expression instead of an if/else:
for (int i = 0; i < studentAnswer.length; i++) {
String origAns = studentAnswer[i];
for (int j = 0; j < key.length; j++) {
points[j] = origAns.charAt(j) == key[j] ? 1 : 0;
}
}
When you call a method in Java, you use parentheses () instead of brackets [].
Since substring is a method, you should call it like so
if (origAns.substring(j) == key[j])
A few other notes, you should use the equals method for comparisons (especially those comparisons involving Strings.)
if (origAns.substring(j).equals(key[j]))
Also, you should use charAt to extract a single character at some position in a string. substring(j) will return a string of characters starting at position j.
if (origAns.charAt(j).equals(key[j]))
Your explanation is very long and I have not read it from the beginning to end. But I can see at least one problem in your code:
if (origAns.substring[j] == key[j])
You are comparing strings using == instead of using method equals():
if (origAns.substring[j].equals(key[j]))
Substring is a function, not a member, of String objects. Check out the example at the top of this page:
http://docs.oracle.com/javase/6/docs/api/java/lang/String.html
Notice the use of parenthesis instead of brackets.
If you are using a String use charAt function
String studentAnswer = "TTFFTFTFTF";
for (int i = 0; i < studentAnswer.length(); i++)
{
char origAns = studentAnswer.charAt(i);
}
Else if you are using an char array then
char studentAnswer[] = "TTFFTFTFTF".toCharArray();
for (int i = 0; i < studentAnswer.length; i++){
char origAns = studentAnswer[i];
}

How To Assign A Value To The First Index In a Multi Dimensional Array In Java

I have a 2d array and I want to know how do you set the first value so if my array was
int array[a][b] = int[10][10];
How would you access index 'a' in a for loop?
This is my simple code that I am working on thanks in advance
int[][] timesTable = new int[12][12];
for(int i = 0; i < timesTable.length; i++){
timesTable[i][i] = i + 1;//can't set the first index with this value
System.out.println(timesTable[i]);
}
I hope you are not putting the "a" and "b" in the array declaration.
int array[][] = int[10][10];
A 2D array is array of arrays. The index "a" or what you are trying to set is another array.
timesTable[i][i] = i + 1;//can't set the first index with this value
The above can be written like this:
timesTable[i] = {1,2,3};// puts another array at index i
You access your array using [], which you'll need to do n times for an n-dimensional array if you're trying to access a particular element.
If you're simply trying to set the first element, then you can do:
array[0][0] = 100; // some number
If you want to iterate over each element in the entire 2d array, you'll need 2 loops, one for each dimension, like so:
for ( int i = 0; i < array.length; ++i ) {
for ( int j = 0; j < array[i].length; ++j ) {
array[i][j] = i + j; // or whatever you want to set the elements to
System.out.println( array[i][j] );
}
}

Categories

Resources