Pregunta

Hey I'm just starting my first programming class with java. In class, we made a very basic code for adding up numbers in a harmonic series. I get an error: cannot find symbol for x on the line total+= (1.0/(x+1)).

Here's the code:

public class Group1
{
public static void main(String[]args)
    {
        foo(3);
    }
public static void foo(int n)
    {
    double total = 0;
    for (int x = 0; x < n; x++);
        {
        total+= (1.0/(x+1));
        }
    System.out.println(total);
    }
}

I would appreciate any answers. I've been messing around trying get it an hour. I can't believe I couldn't find something so simple. Thank you for any help.

¿Fue útil?

Solución 2

Remove semi colon at the end of for statement. Basically in your code scope of variable is inside for loop only and since you are closing the for loop by putting a semi colon, x is gone after that.

Otros consejos

Remove the ; at the end of the for loop. By adding semi colon at the end, you are limiting the scope of the variable x

for (int x = 0; x < n; x++); // <--- remove this semi colon

change for (int x = 0; x < n; x++); to for (int x = 0; x < n; x++)

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top