2014-12-29 4 views
1

아래 튜토리얼 질문을하려고합니다. If 문에서 변수를 확인할 수 없습니다.

import java.util.ArrayList; 
import java.util.Collections; 
import java.util.List; 

public class Ex4_GreatestCommonFactor { 

    // This is the main method that is executed as 
    // soon as the program starts. 
    public static void main(String[] args) { 
     // Call the greatestCommonFactor method a few times and print the results 
    } 

    public static int greatestCommonFactor(int a, int b){ 
     int i = 1 ; 
     while (i >= 1){ 
      i++; 
     } 
     if (a%i == 0 && b%i == 0){ 
      ArrayList factor = new ArrayList<Integer>(); 
      factor.add(i); 
     } 
     else if (a%i <= 1 || b%i <= 1){ 
      Collections.sort(factor); 
      List<Integer> topnum = factor.subList(factor.size() - 1, factor.size()); 

     } 
     return topnum; 
    } 
} 

그래서 나는이 개 질문이 아래
// Create a method called greatestCommonFactor 
// It should return the greatest common factor 
// between two numbers. 
// 
// Examples of greatestCommonFactor: 
// greatestCommonFactor(6, 4) // returns 2 
// greatestCommonFactor(7, 9) // returns 1 
// greatestCommonFactor(20, 30) // returns 10 
// 
// Hint: start a counter from 1 and try to divide both 
// numbers by the counter. If the remainder of both divisions 
// is 0, then the counter is a common factor. Continue incrementing 
// the counter to find the greatest common factor. Use a while loop 
// to increment the counter. 

그리고 내 코드입니다.

1) 내 elseif 문에서 factor을 변수로 해석 할 수없는 오류가 발생합니다. 이전 If 문에서 factor ArrayList를이 elseif 문으로 "이전"하려면 어떻게해야합니까?

2) topnum을 해결할 수없는 유사한 오류가 발생합니다. 내 메서드에서이 코드 줄의 배치 오류입니까, 아니면 완전히 다른 실수입니까?

+0

ArrayList factor = new ArrayList (); – Josh

+2

저는 메서드의 처음 네 줄을 약간 걱정했습니다. '1'에서 시작한다면'i'는 어떻게 될 것이라고 생각합니까? 그리고'> = 1'이 될 때까지 늘리십시오. 그리고 왜 이것을합니까? –

+1

그 동안 루프가 끝나지 않을 것입니다. – Ghokun

답변

1

(다른 자바의 '부분'의 사이) 각 변수 경우에 사용할 수있는 범위를 갖는다. 범위는 일반적으로 변수가 선언 된 블록입니다.

블록 : http://docs.oracle.com/javase/tutorial/java/nutsandbolts/expressions.html

당신의 방법에서

greatestCommonFactor 전체 방법에 유효한 세 가지 변수가있다 : A, B, 내가

당신은 당신이 방법을 처음부터 모든 곳에서 액세스 할 수 있습니다

(첫 번째 오픈 브레이스) 마지막까지 (마지막 닫기 버팀대).

첫 번째 if 문 내부의 블록이 새로운 범위입니다. factor는이 범위에서 선언되며 프로그램 실행이이 블록을 벗어난 후에 더 이상 사용할 수 없습니다.

if (a%i == 0 && b%i == 0){      // Start of Block/Scope 
     ArrayList factor = new ArrayList<Integer>(); // Declaration, you can access factor now 
     factor.add(i); 
    }            // End of Block/Scope, factor inaccessible 

else if 부분은 자체 범위가있는 새 블록입니다.

else if (a%i <= 1 || b%i <= 1){ 
     Collections.sort(factor); 
     List<Integer> topnum = factor.subList(factor.size() - 1, factor.size()); 

    } 

첫 번째 블록에 선언 된 요소가 더 이상 존재하지 않습니다. 선언을 끌어와 if의 바깥에 넣을 수 있습니다.

public static int greatestCommonFactor(int a, int b){ 
    int i = 1 ; 
    while (i >= 1){ 
     i++; 
    } 
    ArrayList<Integer> factor = new ArrayList<Integer>(); 
    if (a%i == 0 && b%i == 0){ 
     factor.add(i); 
    } 
    else if (a%i <= 1 || b%i <= 1){ 
     Collections.sort(factor); 
     List<Integer> topnum = factor.subList(factor.size() - 1, factor.size()); 

    } 
    return topnum; 
} 
3

1) 내 elseif 문에서 factor가 변수로 해석 될 수없는 오류가 발생합니다. 이전 If 문에서 ArrayList 요소를이 elseif 문으로 "옮기는"방법은 무엇입니까? 전에도 선언하여

ArrayList factor = null; 
if (/* some condition */) { 
    // initialize factor 
} else if (/* some condition */) { 
    // access factor here 
} 
+1

일반적으로 위의 경우 변수에'null '을 지정하지 말고 컴파일러가'if/else' 문을 통해 모든 경로를 따라 값을 할당하지 않으면 경고합니다. –

+0

이 경우 컴파일러는 코드가 컴파일되지 않도록 보장하지 않기 때문에 변수가 초기화되기 전에 초기화된다는 점에서 if (초기화 할 때 else에서 액세스하십시오. – MPirious

관련 문제