2013-10-14 2 views
0

다른 while 루프의 변수를 사용하여 print 문에 삽입하는 방법은 무엇입니까?두 개의 다른 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); 
    } 
} 
}