This is in Java
I'm not sure what is wrong with the arrayName.length in my code, it doesn't work on both occasions
for (int i = 0; i<arr.length; i++)
{
for(int j = 0; j < arr2.length; j++)
{
}
}
These two arrays are char arrays and does not seem want to work with the .length method. It says that "length cannot be resolved or is not a field"
Can someone please explain to me why this is happening
You aren't using arrays in your code, you are using ArrayLists. They are totally different and have different methods. The equivalent method to length for ArrayList is .size().
Related
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();
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I have a 2d array of "#" and "." I am Passing into a method, I am then trying to iterate through the array and find how many "#" are in it. I keep getting a NULLPOINTER exception when using .equals. the method should return the amount of "#" in the array. I tried iterating through the 2d Array and then converted the 2d into a single dimension array and still am getting the EXCEPTION Im not sure what I am doing wrong, any help would be greatly appreciated.
my code is:
public static int countSeats(String[][] aud){
int openSeats = 0;
String [] audit;
audit = new String[120];
int k = 0;
for(int i= 0; i < aud.length; i++)
for(int j = 0; j < aud[i].length; j++)
audit[k++] = aud[i][j];
for(int i= 0; i <= audit.length; i++){
openSeats = audit[i].equals("#")? +1:+0;
}
return openSeats;
You're getting an exception because of your loop condition:
for(int i= 0; i <= audit.length; i++){
Notice how you're using <= and not <. You're looping through the entire audit array, and then going one more than you should, resulting in the NullPointerException.
The fact that you declare String[] audit, makes the solution even more complicated as you MAYBE TRY TO PUT ALL THE 2-D in 1-D thinking that it will simplify the problem for you, but it wont. Stay inside the 2-D, and do the search
int openSeats = 0;
for(int i= 0; i < aud.length; i++)
{
for(int j = 0; j < aud[i].length; j++)
{
if( aud[i][j].equals("#") )
{
openSeats++;
}
}
}
return openSeats;
As others have pointed out, you are running your for loop one iteration extra by having i <= audit.length; instead of i < audit.length;. Also, as a good practice, always keep the String literal on the left side of the method call. E.g. instead of aud[i][j].equals("#"), do "#".equals(aud[i][j]) to avoid any possibility of NPE.
Currently working on a student project. I want to figure out the highest number and sort it by bubble sort, the number is parsed from a JLabel, but I get this error everytime. Here is a code snippet:
JLabel[] wuerfelsummen = new JLabel[7];
wuerfelsummen[0] = player1_wuerfelsumme;
wuerfelsummen[1] = player2_wuerfelsumme;
wuerfelsummen[2] = player3_wuerfelsumme;
wuerfelsummen[3] = player4_wuerfelsumme;
wuerfelsummen[4] = player5_wuerfelsumme;
wuerfelsummen[5] = player6_wuerfelsumme;
public int ermittleGewinner(JLabel[] w)
{
int temp;
int[] zahlen = new int[w.length];
for(int i=0; i<=zahlen.length; i++)
{
if(w[i].getText() == null)
{
zahlen[i] = 99999999;
}
else
{
zahlen[i] = Integer.parseInt(w[i].getText());
}
}
for(int i=1; i<zahlen.length; i++)
{
for(int j=0; j<zahlen.length-i; j++)
{
if(zahlen[j]>zahlen[j+1])
{
temp=zahlen[j];
zahlen[j]=zahlen[j+1];
zahlen[j+1]=temp;
}
}
}
for(int i=0; i<=zahlen.length; i++)
This is incorrect, as arrays are 0-indexed, meaning they reach from 0 to length-1.
Change it to
for(int i=0; i<zahlen.length; i++)
Interestingly enough, your other loops avoid this pitfall, although you will still have to be careful about the j+1 later on. Make sure that this can never be >= zahlen.length.
You could simply initialize j with 1 instead of 0 and then replace all occurences of j with j-1 and j+1 with j
change "i<=zahlen.length" in your for loop to "i < zahlen.length".
remember arrays are 0 indexed so you are trying to access an element one index outside of how large your array is with the "<=" method you are currently using
The second loop should start at i=0 instead of i=1. By using i=1, you are again going to try to access one element past the size of your array
ArrayIndexOutOfBounds expcetion comes when code tried to access an element of an array which is not present. In your code, since you are FOR looping one extra time for(int i=0; i<=zahlen.length; i++), you are getting this exception. Keep FOR loop as for(int i=0; i<zahlen.length; i++)
You have not to just check for zahlen[i] but also for w[i] because you are looping on length of zahlen and it may so happen that w is of lesser length then zahlen.
I've a slight problem. I'm taking every element in a sparse matrix and putting it into a 1d array named 'b[]'. For example:
00070
00400
02000
00050
10000
Becomes: 0007000400020000005010000
The code below works in that at a given point within the inner-most loop b[] has the correct value as shown below. My problem is that outside of the inner-most loop b[] has a value of:
b[] = 0000000000000000000000000
I cannot understand what I'm missing. It should also be noted that b[] is globally defined, and instantiated within the constructor of this class. The problem is that I'm trying to use this 1d array in another function, and every element within the array is set to 0.
public void return1dSequence() {
// Create paired objects (Pair class).
for (int i = 0; i < a.length; i++) {
for(int j = 0; j < a[i].length; j++) {
this.b[i] = a[i][j];
// System.out.print(b[i]);
if (this.b[i] == 0) {
pos += 1;
} else {
value = this.b[i];
ml.add(new Pair(pos, value));
pos += 1;
}
}
}
}
Thanks in advance for any replies,
Andre.
You're filling in b[i] for indexes i of your outer loop...
Each time in the inner loop, you overwrite b[i] with value a[i][j].
Last value of a[i] array is always zero.
That's why your b array is zero.
What you want is probably:
int counter = 0;
for (int i = 0; i < a.length; i++) {
for(int j = 0; j < a[i].length; j++) {
b[counter] = a[i][j];
counter++;
}
}
The first thing i want to mention is that u shouldn't declare your variables (a, b....) static. Maybe u got hit by a mean side effect after creating two instances of Sparse. Try to define them as non static and report if it still wont work.
Best regards
Thomas
Try removing this from each call to b[] if you want to access b[] as static.
Also, are you sure you are not overwritting b[] anywhere else in the code? This is most likely the issue because of the public static declaration. Try making it private and removing static and see if you still have the issue.
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];
}