1

This method will not compile, can't see why. Error is:

Can't find symbol-variable i

The int i is defined in the for-loop. The method should return the even numbers between int a and int b.

The code:

public int partall(int a, int b){
    int partall;
    int største; 
    int minste;
    if(a == b){
        partall = 0;
    }else{
        if(a>b) {
        største = a;
        minste = b; 
        }else if(a<b){
            minste = a;
            største = b;

            for(int i = minste;  i<= største; i++){
                if(i % 2 == 0) {
                     partall = i;
                }
            }

        }

    }
    return i;
}
Tunaki
  • 132,869
  • 46
  • 340
  • 423
Akarlsen
  • 31
  • 3

4 Answers4

2

i is only visible in the scope of for loop, but not outside. When you do return i; it is out of scope. So you need to put the declaration outside of for block.

Solution:

public int partall(int a, int b){
    int partall;
    int største; 
    int minste;
    int i = 0; 
    if(a == b){
        partall = 0;
    }else{
        if(a>b) {
            største = a;
            minste = b; 
        }else if(a<b){
            minste = a;
            største = b;

            for(i = minste;  i<= største; i++){
                if(i % 2 == 0) {
                    partall = i;
                }
            }

        }

    }
    return i;
}
u32i64
  • 2,384
  • 3
  • 22
  • 36
1

You are returning i which has scope only in for loop not outside that.

From the implementation, I think you might probably want to return partall but not i.

Initialize partall with something, i.e.

int partall = 0;

and in the last line

return partall;

That should work

Anand Undavia
  • 3,493
  • 5
  • 19
  • 33
0

The variable i is not visible in the scope of the return statement. You need to declare i outside of the for loop and outside of the if-else for it to be visible in the scope of the return. Try declaring int i = 0; (or even int i = minste; and remove the assignment below) at the top of the function where you declare the rest of your variables.

Max Weinzierl
  • 1,231
  • 10
  • 13
0

you should initialize "partall" and return that variable:

public int partall(int a, int b){
    int partall = 0;
    int største; 
    int minste;
    if(a == b){
        partall = 0;
    }else {
        if(a>b) {
        største = a;
        minste = b; 
    } else if(a<b) {
        minste = a;
        største = b;

    for(int i = minste;  i<= største; i++){
        if(i % 2 == 0) {
            partall = i;
        }
    }

   }

}
return partall;

}