0

so , while making a code in java there is a problem that variable should initialized so that it work in the code , but I want to use the variable without initializing any value to it ,

class Solution{

public static void main(String []argh){
   
    
     int a;
     int b ;
      int n ;
      Scanner in = new Scanner(System.in);
     int t = in.nextInt();
    for(int i=0;i<t;i++){
           a = in.nextInt();
        b = in.nextInt();
         n = in.nextInt();
    }
    
    int sum=0;
    for (int i =0;i<=n; i=i*2)
    {
        sum=a+i*b;
        System.out.print(sum);
    }
    
  }
}

the above code is throwing the error that the variable is not initialized , but i don't want to initialize it and i want to use them again and again without initializing again and again.

  • Why do you want to use the variable without initializing it? What do you expect to happen? – Green Cloak Guy Oct 18 '21 at 16:03
  • so that i can use , the variable in for loop or outside of the loop without declaring them again and agian –  Oct 18 '21 at 16:06
  • 1
    @DevanshKumar - You can declare a variable outside a for loop, and use it in the for loop, as long as you assign it a value before attempting to use its value. This eliminates what was a common cause of error in some other languages. – Andy Thomas Oct 18 '21 at 16:09
  • my professor had told a method , by using object we can use them , i forget the method which he told –  Oct 18 '21 at 16:17
  • Scanner is an object. and nextInt is a method. You will need `int t = in.nextInt()` before your loop – OneCricketeer Oct 18 '21 at 16:18
  • yeah , there is one , i forget to put that in above code ,thanks!! –  Oct 18 '21 at 16:19
  • The second loop uses the value of `a`, but it may be unassigned, if the body of the first loop was never executed. You could avoid this by definitely assigning `a` a value -- e.g., in the declaration with `int a=0;`. However, defining two variables with small scopes can serve you better than declaring one variable in a large scope with two different purposes. – Andy Thomas Oct 18 '21 at 17:52

0 Answers0