0

如何使用来自不同 while 循环的变量并将它们插入到打印语句中?

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

4 回答 4

2

我想这是你的答案

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);
  }
 }
}
于 2013-10-15T08:22:02.863 回答
1

在循环外声明变量,并在循环内为它们分配值!

于 2013-10-14T18:34:04.457 回答
0

您需要在循环外声明局部变量一和二

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);
   }
 }
于 2013-10-14T18:47:02.203 回答
0

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);
  }               
}
于 2013-10-14T18:33:53.640 回答