2013-10-14 65 views
0

如何使用來自不同while循環的變量並將它們插入到打印語句中?使用來自兩個不同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); 
    } 
} 
+0

我只得到一個線的時候我應該得到一些 – jenncar

+0

是什麼你真的想要做什麼?發佈你的問題陳述? –

+0

您的打印聲明只會執行一次。考慮在循環內移動它。 – Zavior

回答

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

這是相當廣泛的,因爲有很多方法可以做到這一點。您只需要將循環內的結果收集到全局變量中。如果你想專門製作一個字符串,那麼你可以使用類似StringBuilder的東西。

這裏是與數字之間沒有空格的例子:

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

你也可以把變量分爲數組,等:

ArrayList<Integer> list = new ArrayList<Integer>(); 
while (counterA < 51) { 
    counterA++; 
    if (counterA % 5 == 0){ 
    list.add(counterA * counterA); 
    }    
} 
1

聲明變量,你的循環之外,併爲它們分配的循環內的值!

3

我覺得這是你的答案

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