For문 응용(sum_2, sum_3)

양혜정·2024년 1월 27일
0

Begin_java

목록 보기
24/71

응용. 입력한 값이 숫자(int)가 아닌 경우

int sum = 0;		// 누적의 합을 저장하는 변수로, 0으로 초기화
String str = "";	// 누적할 숫자와 +,= 을 문자열로 결합하는데 이용

for(;;){	// 무한루프
	try{	// 오류발생 시 catch 문으로 이동
    	System.out.print(">> 누적해야할 시작 숫자 => ")
        int start_no = Integer.parseInt(sc.nextLine());
        // nextLine()이 String 타입이기에 int 타입으로 변환
        System.out.print(">> 누적해야할 마지막 숫자 => ")
		int end_no = Integer.parseInt(sc.nextLine());
        
        ================================================
        [cnt 를 이용]
        int cnt = end_no - start_no + 1;
        // cnt = 반복해야할 횟수
        
        for(int i=0;j=start_no; i<cnt; i++,j++){
          // 방법1
            if(i<cnt-1) {
                str += j + "+";
            } else {
                str += j + "=";
            }
          sum += j;
        
          // 방법2
          String add = (i<cnt-1)?"+":"=";
          str += j + add;
          sum = += j;
          
      	}	// end of for-------------------------
       ================================================
        
        [삼항연산자 이용]
        for(int i=start_no; i<=end_no; i++){
        String add = (i<end_no)?"+":"=";
        str += i+add;
        sum += i;
        }	// end of for--------------------
        ================================================
   } catch(NumberFormatException e) {
   		System.out.println("[경고] 올바른 정수만 입력하세요!!");
        continue;	// 다시 입력할 기회를 준다.
        			// break; 시 다시 입력할 기회 X
        }
   sc.close();
   break;	// for 문을 빠져나간다.
   }	// end of for----------------------------
   
   System.out.println(str+sum);
	// 시작숫자 + (시작숫자+1) + ...+ (마지막숫자-1) + 마지막숫자 = 합

참고

삼항연산자 : https://velog.io/@jjoung-2j/%EC%97%B0%EC%82%B0%EC%9E%90

정리

my.day05.e.For -> Main_for_5_sum_2, Main_for_5_sum_3

0개의 댓글

관련 채용 정보