Search code examples
javavariablesloopswhile-loopscoping

Using variables from two different while loops


How do I use variables from different while loops and insert them in a print statement?

 public class Squares{
   public static void main (String [] args){
      int counterA = 0;
      int counterB= 0;

      while (counterA<51){
           counterA++;
           if (counterA % 5 == 0){
                int one = (counterA*counterA);
           }               
      }
      while (counterB<101){
           counterB++;
           if (counterB % 2 == 0){
                int two = (counterB*counterB);         
           }    
      }
       System.out.println(one+two);
   }
 }

Solution

  • you need to declare the local variables one and two outside the loops

    public class Squares{
       public static void main (String [] args){
          int counterA = 0;
          int counterB= 0;
          int one=0;
          int two=0;  
    
          while (counterA<51){
               counterA++;
               if (counterA % 5 == 0){
                    one = (counterA*counterA);
               }               
          }
          while (counterB<101){
               counterB++;
               if (counterB % 2 == 0){
                    two = (counterB*counterB);         
               }    
          }
           System.out.println(one+two);
       }
     }