I'm having a few problems while developing the following code in Java:
setPos(x, y);
for (int i = 0; x < size; i++) {
for (int j = 0; y < size; j++) {
if (board[x][y] == 'K')
{
System.out.println("You've found a key! CONGRATS!");
return true;
}
Eclipse notice me that i and j, as local variables, they're not used : The value of the local variable i is not used . If I change the i and write the x instead, it tells me that I'm repeating the variable.
j++ is tagged as dead code ?
Also, I have to search for a concrete type of element on the diagonal of a bidimensional array, I've been trying this with 2 for loops, as above, but no result yet.
Hope you can help me, thanks in advance!
Eclipse notice me that i and j, as local variables, they're not used
That's because you're not using them. You've assigned them values, and you've later incremented (added to) those values, but you've never used them for anything.
j++ is tagged as "dead code" (?)
For the same reason, the code increments the value of j, but j is never used, so the code does nothing. "Dead code" refers to code that has no purpose or which is never run.
Your loops don't make a lot of sense. For instance:
for (int i = 0; x < size; i++) {
Normally with a for loop, the control variable (i in this case) should appear in all three of the parts of the for statement (the initializer, the test, and the increment), like this:
for (int i = 0; i < size; i++) {
// Change here -^
But you're not doing that, you're only using i in the initializer and the increment, never in the test (x < size). The same is true of your loop with j.
Similarly, unless there's something changing the value of x, y, and/or size, then your loops will either never run (because x or y is already >= size), run once (because it happens that board[x][u] == 'K'), or they'll run forever (because x or y is < size and since nothing changes that, they just keep looping...).
Eclipse is giving you a hint where the error is:
for (int i = 0; x < size; i++) {
for (int j = 0; y < size; j++) {
you iterate over i and j, but you specify x < size and y < size as a condition. Thus you never actually use the i and j value, thus j++ and i++ is dead code.
If you really would like to use a loop, you should use the variable you use for iteration in the for-loop's condition:
for (int i = 0; i < size; i++) { // i instead of x
for (int j = 0; j < size; j++) { // j instead of y
Also, I have to search for a concrete type of element on the diagonal of a bidimensional array, I've been trying this with 2 for loops, as above, but no result yet.
Why not use a single for loop, like this:
for(int i = 0; i< size; i++)
if(board[i][i] == 'K')
{
System.out.println("You've found a key! CONGRATS!");
return true;
}
Look at this:
setPos(x, y);
if (board[x][y] == 'K') //no i or j so they are unused.
{
System.out.println("You've found a key! CONGRATS!");
return true;
}
If I change the i and write the x instead, it tells me that I'm repeating the variable.
Because x is already a variable(your function argument).so you can't declare it again.
dead code : Code that has no effect on programme.Dead code
Note:it's not a solution of your problem(because i don't know). it is just to show you the mistake.
Related
I'm a student currently learning java at school (Beginner) and I was wondering about something.
I have a basic knowledge of coding from other languages and I don't understand a particular thing in Java.
If I were to declare a variable (let's use an int as a example) inside a loop wouldn't that mean that I'm declaring the same variable over and over?
This is what I mean:
for (int i = 0; i < 3; i ++) {
int x = 5;
}
Isn't it the same thing as this? (This one is incorrect)
int x = 5;
int x = 5;
If not, Why? Both of them are / declare the same variable twice, though I know that in loops the variable is local and can't be used outside of the loop (I don't think thats the issue though).
I also know that you can't declare the same variable twice so I don't understand how the first example is legal.
Thanks so much :D
This Question has be solved, Thanks to everyone that helped :D
for (int i = 0; i < 3; i ++) {
int x = 5;
}
is actually equivalent to:
{
int x = 5;
}
{
int x = 5;
}
{
int x = 5;
}
Each x variable is declared in a separate scope.
scope is in one iteration, after end of loop, scope doesn't exist.
simple example:
for (int i = 0; i < 4; i++) {
int x = 0;
System.out.println(x);
x++;
}
output:
0
0
0
0
Lets take 1st expression
for (int i = 0; i < 3; i ++) {
int x = 5;
}
Here scope of variable x is within the loop block
So each time a new loop starts scope is already released.
So there is no error
If you change the same code to like this
for (int i = 0; i < 3; i ++) {
int x = 5;
int x = 5;
}
Now there will be an error as x is already in scope and you are again trying to define.
This is allowed
for (int i = 0; i < 3; i ++) {
int x = 5;
x = 5;
}
as you are resigning the variable
the variable x has life time that begin at when you declare it and ends at the closing block for the for-loop.
in other word x is born when you enter new iteration and dies when iteration ends (or dies at the end of block that contains it)
In each iteration of your loop, a variable x of type int is "created" and assigned the value 5. As soon as the iteration finishes, this variable is "destroyed" and by the next iteration the cycle starts again.
So there are never 2 variables by the same name in the same scope.
It is generally good practice to make the variable avayable to the smallest context possible: if you only need it inside the loop declaring it inside it is considered good practice.
For the loop declaration case, your value gets reassigned basically.
This might proove interesting to read and add further informations on the matter: Declaring variables inside or outside of a loop
This is also a legal thing to do
for (int i= 0; i < 1000000000; i++) {
int j = i & i+1 ;
}
These are legal because at the end of the loop the declared variable "ceases to exists" in order to be reformed the next execution
Well, when you declare int x = 5; inside the loop, you're declaring it in a local scope (which starts from its { to }) so the variable x will be destroyed when it gets out of its scope which means for the next loop iteration, it's a new x so that's why you can do that and since it's destroyed when it gets out of scope it can't be used/seen outside the scope.
Just to clarify the concept of allowing variable declaration in a loop, I've declared the same variable again in the loop, and got error "A local variable or function named 'x' is already defined in this scope"(I wrote this code in C#, but you should get similar message in Java):
If I declare the variable in a different scope outside the loop, there will be no error as the scope is different:
for (int i = 0; i < 3; i++)
{
int x = 5;
}
{
int x = 5;
}
If we couldn't declare variables in loop, we had to write the following code:
{
int x = 5;
// Do something with x=5
}
{
int x = 5;
// Do something with x=5
}
{
int x = 5;
// Do something with x=5
}
But with loop, we can just write the following instead of writing 3 scopes:
for (int i = 0; i < 3; i++)
{
int x = 5;
// Do something three times with x=5
}
Take a look :
int[] v = new int[10];
for (int i = 0; i < v.length; i++) {
for (int j = i + 1; j < v.length; j++) {
if (v[i] > v[j]) {
aux = v[i];
v[i] = v[j];
v[j] = aux;
}
}
}
This works perfecly. But can someone explain how?
How this array DOES NOT goes out of bounds even if I start j with i + 1 ? How does this works?
You have confused the initialization with condition. The syntax for for loop() is-
for(initialization; condition; updation)
{
statement(s)
}
So even if you start j from 1 ( j = i+1 and initial value of i = 0), j will update only till it is equal to the length of the array v i.e., 10. So the moment, j = 10 ( when i = 9), the control will come out of j for loop() and when it will transfer to i for loop(), i will be updated to 10, thus meeting it's condition and moving the control out of i for loop() also.
I think you need to go back to basics on for loops
a for loop can be defined as for(before starting;continue when true;do at end of pass))
So it doesn't matter what your start value is, as soon as j is equal to v.length it will stop. It just does 1 less loop that if you started at i.
Your for loops are made up of a variable to keep track, the condition and the iteration. In your code, the condition of the for loops states that the variable that is keeping track cannot go past the length of v. Therefore, during the sort (because that's what the code is), the inner loop compares all of v's values using j as the index to swap if they meet the if condition. The outer loop is just there to make sure that each index of v is checked and are in the right place.
I have 2 loops like this
goodexpressions and badexpressions are string arrays
for(int i =0; i < goodexpressions.length; i++) {}
&
for(int j =0; j < badexpressions.length; j++) {}
i'm trying to declare both of these in one loop, i've got this so far but it's not correct
for(int b = 0 , c = 0; b < goodexpressions.length; b++ c < badexpressions.length; c++)
what am I supposed to do to correct this statement?
Although what you are trying to do seems like a bad idea, here is a piece of code that will work. I don't know if it does exactly what you want it to though, since that isn't completely clear to me.
for(int b = 0, c = 0; b < goodexpressions.length || c < badexpressions.length; b++, c++) { }
When doing this, though, you still have to check if b and c are inside the array index range. You can also replace the || with && in which case you won't have to do that anymore, but you will be missing some items if the arrays are not equally long.
I think this will do what you are asking:
for (int b = 0, c = 0;
b < goodexpressions.length && c < badexpressions.length;
b++, c++)
Note that there are exactly 2 semicolons separators on an old-style for loop.
And based on your comment, I think this might be better:
for (int i = 0; i < Math.min(goodexpressions.length, badexpressions.length); i++)
Notes:
It is not at all clear what the loop body is going to do. That will determine the right way to combine the loops ... or if it is just a bad idea to combine them at all.
The above code is designed to stop at the smaller of the two lengths. If you want to stop at the larger, change && to || and min to max. However, if you do that, you also need to take care to avoid array bounds exceptions.
Unless the intent is to use both goodexpression[i] and badexpression[i] at the same time (e.g. compare them, combine them, and so on), your code will be more readable and more efficient if you use two separate loops.
Another possibility might be to simply check that the two arrays have the same length.
Depending on what you want to achieve, you should do one of the following. Say you have two lists A and B...
If you want to loop over all the elements in both lists A and B, create a new list, or array, holding the elements of both lists and loop over that list.
for (int i = 0; i < combinedAandB.length; i++) {
...
}
If you want to loop over all the combinations of elements from list A and list B, you have to use nested loops.
for (int i = 0; i < A.length; i++) {
for (int k = 0; k < B.length; k++) {
...
}
}
Update: Concerning the two-variable for-loop approach in your question and the other two answers: Note that since both those variables will take on exactly the same values in each iteration of the loop, you can just as well use just one variable:
for (int i = 0; i < goodexpressions.length || i < badexpressions.length; i++) { }
But also note that this will not do you any good in terms of avoiding code duplication, since you still have to everything to both, goodexpressions[i] and badexpressions[i]. A better approach might be to write a method holding the loop and calling that method once with goodexpressions and once with badexpressions.
I'm making a pretty simple java-program and I get the following error (where n is a random number based on previous input from console):
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: n
the line that is supposed to cause trouble is the if-statement here:
for(int i = 0; 0 < x; i++){
if(TalArray[i] < min){
min = TalArray[i];
}
}
the variable "min" is previously initzialized to TalArray[0] and is keeping track of the lowest number. All variables mentioned are int-variables
The correct code is...
for(int i = 0; i < x; i++){
if(TalArray[i] < min){
min = TalArray[i];
}
}
It's not clear what's the value of x in the code, but anyway the loop condition should look like this:
for (int i = 0; i < TalArray.length; i++)
Or like this, to avoid accessing the length at each iteration:
for (int i = 0, x = TalArray.length; i < x; i++)
The 0 < x comparison is mistaken: you're not modifying the value of x inside the loop, so the loop will either enter an infinite loop or not enter the loop at all, depending on the initial value of x.
The problem is, that your variable X is never changing so
your condition 0 < x is always true.
I guess the correct condition would be
for(int i = 0; i < x; i++)
I'm working on this bacteria life game thing I have to make.
Basically I have a 2d string array let's say 20 by 20.
What would be the best way to check all 8 spots around a certain index. Each index is suppose to represent a bacteria. For each bacteria(index) I have to check to see if any of the 8 spots around this index has another bacteria in it, if the index has a bacteria in it, it's represented simply by a "*", asterik.
What would be the best way to go about checking all 8 spots around each index, because based on what is in the indices around a certain index I have to make certain changes etc.
The only idea I have come up with is having a bunch of if statements to check all 8 spots, I was wondering if there is a better way to do this
ex:
row 1 - www , row 2 = wOw , row 3 - www ,
if I am at the O index, what would be the best way to check all the index spots around it for a certain string.
Sorry, I am not very good at explaining my problems, bad english :o.
thanks for any of the help.
so you have something like this
char[][] table = new char[20][20]
for(int i = 0; i < 20; i++) {
for(int j = 0; j < 20; j++) {
int surroundingBacteria = 0;
for(int x = max(i-1,0); x < min(20,i+1); x++) {
for(int y = max(i-1,0); y < min(20,i+1); y++) {
if(table[x][y] == '*') surroundingBacteria++;
}
}
switch(surroundingBacteria) {
// put your case logic here
}
}
}
Here is how I've accomplished this in the past:
for(int x = -1; x<=1; x++){
if ( i+x < xLength && i+x >= 0){
for(int y = -1; y<=1; y++){
if(j+y < yLength && j+y >= 0){
//logic goes here
}
}
}
}