[英]Using variables from two different while loops
如何使用來自不同while循環的變量並將其插入到print語句中?
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);
}
}
我想這就是你的答案
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);
}
}
}
在循環外聲明變量,並在循環內為它們分配值!
這是相當廣泛的,因為有很多方法可以做到這一點。 您只需要將循環中的結果收集到全局變量中即可。 如果要專門制作一個字符串,則可以使用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和2
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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.