2012-10-15 2 views
1

나는 자바에서 그논리 조합 자바 방법 : 첫 번째는 이미 거짓이면

if(a!=0 && b/a>1){ 
    ...; 
} 

자바 등의 작업을 수행하는 것이 매우 편리합니다 첫 번째 부분 인 경우 중지 알고 두 번째 경우를 테스트하지 마십시오 이미 거짓. R은 그렇게하지 않아 때때로 오류가 발생합니다. 그래서 : 또한

if(exists("user_set_variable")){ 
    if(user_set_variable < 3){ 
     ... 
    } 
} 

답변

3

당신이

& and && indicate logical AND and | and || indicate logical OR. 
The shorter form performs elementwise comparisons in much the same 
way as arithmetic operators. The longer form evaluates left to right 
examining only the first element of each vector. Evaluation proceeds 
only until the result is determined. The longer form is appropriate 
for programming control-flow and typically preferred in if clauses. 

그래서 아마 당신이 & 대신 &&을 찾고 찾을 수 있습니다 (여기 x가 존재하지 않습니다).

# Case 1 
a<- 2 
b <- 4 

if(a!=0 & b/a>1){ 
    print('Hello World') 
} else{ 
    print("one or both conditions not met") 
} 
[1] "Hello World" 

# Case 2 
a<- 2 
b <- 1 

if(a!=0 & b/a>1){ 
    print('Hello World') 
} else{ 
    print("one or both conditions not met") 
} 
[1] "one or both conditions not met" 


# Case 3 
a<- 0 
b <- 1 

if(a!=0 & b/a>1){ 
    print('Hello World') 
} else{ 
    print("one or both conditions not met") 
} 
[1] "one or both conditions not met" 
+0

이 예제는 두 번째 조건에서 오류가 발생하고 오류가 발생하지 않아 단락 회로가 명확하게 표시되는 경우 표시하는 것이 더 유용 할 것이라고 생각합니다. –

+0

감사합니다. @ CarlWitthoft, 매우 도움이되는 의견입니다. 나는 이미 내 대답을 편집했다. –

+0

분명히 필요한 '&&'버전입니다. 'b/a'는'a = 0'에 대해서 R에 에러를 발생시키지 않고, 문제없이 유한 값과 비교할 수있는'Inf'를 생성합니다. – James

5

R 단락 두 번째 인수가 평가 될 필요가 없습니다 &&|| 운영자 :이 코드는 짧은 만들 수있는 가능성이있다. 예를 들어 ?'&&'에서

> if (exists('x') && x < 3) { print('do this') } else { print ('do that') } 
[1] "do that" 
0

을 어느있는 그대로 사람들은 충분히 명확하거나 그냥 함수로 문을 줄 경우 여러 포장 할 수 있다면 단락 문을 사용 : 두 가지 조건이 평가되는 예제를 참조하십시오. 다음은 시각적 인 의사 코드입니다.

(가) ("user_set_variable"존재하는) 경우 {(user_set_variable < 3) { 가 ...} 경우}

은 다음과 같을 수

var<- "user_set_variable" 'let var be your variable for this 
if(exists(var) && var < 3) 
{ 'do stuff } 

또는이 작업을 수행 :

'function definition 
Function boolean IsValidVar(variable) 
{ 
    if(exists(var)) 
    { 
     if(var < 3) 
     { return true; }} 
    return false; 
} 

다음과 같이 프로그램이 표시됩니다.

var<- "user_set_variable" 'let var be your variable for this 
if(IsValidVar(var)) 
{ 'do stuff } 

단순한 것처럼 보이는 것은 사용자의 전화입니다.

관련 문제