+ 2
Why is my If else statement not working correctly?
I formatted it correctly yet it still gives me error. this program is for the find the black box challenge. https://code.sololearn.com/c2JyX7EXoPtZ/?ref=app
3 Respuestas
+ 6
:::: YOUR ERROR ::::::
..\Playground\:15: error: 'else' without 'if'
} else {
^
1 error
^As you can see by the error, it's telling you exactly what's wrong. You have an 'else' that isn't tied into an IF statement. It even tells us what line.
:::: LINES 13 - 17 :::::
if(num < 20 && num > 10 ) {
System.out.println("Correct"); }
} else {
System.out.println("Incorrect"); }
}
^If you look at line 14, you have a stray closing brace at the end. If you look at line 16, you did the same thing. For each block, you want one set of { }.
Also, num is an array, but you were using it as a normal int. So you'll want to fix that by adding its index.
:::: CORRECTED CODE :::::
https://code.sololearn.com/cdEN8hN37r7J/#java
import java.util.Random;
public class FindBlackBoxChallenge
{
public static void main(String[] args) {
Random ran = new Random();
int[] boxes = new int[100];
int[] num = new int[100];
for(int x = 0; x < boxes.length; x++) {
boxes[x] = ran.nextInt(100);
//System.out.println();
}
for(int y = 0; y < num.length; y++) {
num[y] = ran.nextInt(21);
System.out.println(num[y]);
if(num[y] < 20 && num[y] > 10 ) {
System.out.println("Correct");
} else {
System.out.println("Incorrect"); }
}
}
}
+ 2
thanks, I appreciate it. have a good day
0
If you want to make the readability of your code better and easier to understand, then learn about the java language conventions. Your code is not properly formatted.
In the first for loop your code print unnecessary empty lines. Perhaps the print statement is supposed to be out of the loop body.
In the condition in the second for loop you compare reference variable with integer. There is unnecessary closing curly brace, before the else body.
Here is your code fixed:
import java.util.Random;
public class FindBlackBoxChallenge {
public static void main(String[] args) {
Random ran = new Random();
int[] boxes = new int[100];
int[] num = new int[100];
for(int x = 0; x < boxes.length; x++) {
boxes[x] = ran.nextInt(100);
}
System.out.println();
for(int y = 0; y < num.length; y++) {
num[y] = ran.nextInt(21);
System.out.println(num[y]);
if(num[y] < 20 && num[y] > 10 ) {
System.out.println("Correct");
} else {
System.out.println("Incorrect");
}
}
}
}