-3

I don't understand what is wrong with my code and why it produces error:

variable k might not have been initialized

import java.util.*;
public class kk
{
    public static void main(String [] args)
    {
        Scanner scan=new Scanner(System.in);
        int m=scan.nextInt();
        for(int q=0;q<m;q++)
        {
        int a=scan.nextInt();
        int b=scan.nextInt();
        int n=scan.nextInt();
        scan.close();
        int k;
        for(int i=1;i<=n;i++)
        {
            for(int j=1;j<=i;j++)
            {
               k=j*b;
            }
            k=k+a;
            System.out.println(k);
            k=0;
        }}
    }
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
pranav
  • 1
  • 1
  • 4
  • The error is quite clear; you're declaring the variable but not initializing it with a value before the loop. – Mick Mnemonic Sep 18 '17 at 22:16
  • What should the value of `k=k+a;` be if `k` was never given an initial value? – azurefrog Sep 18 '17 at 22:18
  • As the warning says. the variable `k` is not initialized. In Java, **local variables** are not initialized as default unlike **instance variables**. Local variables have to be initialized manually, e.g, `int k = 0` – Indra Basak Sep 18 '17 at 22:28

2 Answers2

0

Not sure what your main method/code is trying to accomplished but the variable int k is being considered as a local variable in your case. Please consider initializing your int primitive data type variable k with the default value of 0 before using it in the nested for-loop code block.

int k = 0;

From the Java documentation:

Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable. If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Tekle
  • 176
  • 2
  • 7
-2
public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int m = scan.nextInt();
    for (int q = 0; q < m; q++) {
        int a = scan.nextInt();
        int b = scan.nextInt();
        int n = scan.nextInt();
        scan.close();
        int k;
        for (int i = 1; i <= n; i++) {
            k = 0;
            for (int j = 1; j <= i; j++) {
                k = j * b;
            }
            k = k + a;
            System.out.println(k);
        }
    }
}
Notwen
  • 1