如何使用来自不同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);
}
}
答案 0 :(得分: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);
}
}
}
答案 1 :(得分:1)
声明循环外的变量,并在循环内为它们赋值!
答案 2 :(得分: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);
}
}
答案 3 :(得分:0)
你需要在循环之外声明局部变量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);
}
}