Hi, started programming 2 days ago, and i'm having a problem with Java saying one of my variables isn't initialised. Couls someone help please?! Thanks, code below:

public static void adding()
    {

        int n = getN();
        int total;

        for (int i=1; i<=n; i++)
        {
            total = i + 1;
        }

        System.out.println(total);
    }

    public static int getN()
    {
        String input = JOptionPane.showInputDialog(null,
                                        "How many numbers would you like to add up?");
        int n = Integer.parseInt(input);

        return n;
    }

and the error code:

adding.java:22: error: variable total might not have been initialized
        System.out.println(total);
                           ^
1 error

I'm trying to create a program that asks for a number (n) and then the program adds all the numbers up to n (e.g. 1 + 2 + 3 etc.). Thanks!

local variables don't have default values. now, let's assume that n = 0, that's a possibility the compiler takes into account: your for loop will never run, so total will not get a value, and then, you try to print an int without a value.

just change

int total;

into

int total = 0;