سؤال

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);
   }
 }
هل كانت مفيدة؟

المحلول 3

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);
   }
 }

نصائح أخرى

I think this is your answer

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

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

Declare the variables outside your loop, and assign them the values inside the loop!

This is quite broad, as there are many ways to do this. You just need to collect the results from within the loops into a global variable. If you want to specifically make a string, then you can use something like a StringBuilder.

Here is an example with no spacing between numbers:

StringBuilder sb = new StringBuilder();
int counterA = 0;
int counterB = 0;

while (counterA < 51) {
  counterA++;
  if (counterA % 5 == 0){
    sb.append(counterA * counterA);
  }               
}
while (counterB<101) {
  counterB++;
  if (counterB % 2 == 0) {
    sb.append(counterB * counterB);         
  }    
}
System.out.println(sb.toString());

You can also put the variables into arrays, etc:

ArrayList<Integer> list = new ArrayList<Integer>();
while (counterA < 51) {
  counterA++;
  if (counterA % 5 == 0){
    list.add(counterA * counterA);
  }               
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top