Java if 문의 약식
Java if
문을 짧은 형식으로 작성하는 방법이 있다는 것을 알고 있습니다 .
if (city.getName() != null) {
name = city.getName();
} else {
name="N/A";
}
누구든지 위의 5 줄에 대한 짧은 양식을 한 줄에 쓰는 방법을 알고 있습니까?
삼항 연산자를 사용하십시오.
name = ((city.getName() == null) ? "N/A" : city.getName());
조건이 거꾸로 있다고 생각합니다. null 인 경우 값이 "N / A"가되기를 원합니다.
도시가 null이면 어떻게 되나요? 이 경우 코드가 침대에 닿습니다. 다른 수표를 추가하겠습니다.
name = ((city == null) || (city.getName() == null) ? "N/A" : city.getName());
.getName()
두 번 전화를 피하려면
name = city.getName();
if (name == null) name = "N/A";
이를 수행하는 방법은 삼항 연산자를 사용하는 것입니다.
name = city.getName() == null ? city.getName() : "N/A"
그러나 위 코드에서 오타가 있다고 생각합니다.
if (city.getName() != null) ...
? : Java의 연산자
Java에서는 다음과 같이 작성할 수 있습니다.
if (a > b) {
max = a;
}
else {
max = b;
}
단일 조건을 기반으로 단일 변수를 두 가지 상태 중 하나로 설정하는 것은 if-else의 일반적인 사용으로 조건부 연산자? :에 대한 바로 가기가 고안되었습니다. 조건부 연산자를 사용하면 위의 예제를 다음과 같이 한 줄로 다시 작성할 수 있습니다.
max = (a > b) ? a : b;
(a> b)? a : b; a 또는 b의 두 값 중 하나를 반환하는 표현식입니다. 조건 (a> b)이 테스트됩니다. 참이면 첫 번째 값 a가 반환됩니다. False이면 두 번째 값 b가 반환됩니다. 반환되는 값은 조건부 테스트 a> b에 따라 다릅니다. 조건은 부울 값을 리턴하는 표현식 일 수 있습니다.
자바 8 :
name = Optional.ofNullable(city.getName()).orElse("N/A")
나는 항상 ?:
삼항 연산자 를 사용하는 방법을 잊고 있습니다 . 이 보충 답변은 빠른 알림입니다. 의 약칭입니다 if-then-else
.
myVariable = (testCondition) ? someValue : anotherValue;
어디
()
보유if
?
방법then
:
방법else
와 동일
if (testCondition) {
myVariable = someValue;
} else {
myVariable = anotherValue;
}
if, else if, else
짧은 형식으로 진술을 작성할 수 있습니다 . 예를 들면 다음과 같습니다.
Boolean isCapital = city.isCapital(); //Object Boolean (not boolean)
String isCapitalName = isCapital == null ? "" : isCapital ? "Capital" : "City";
이것은 짧은 형식입니다.
Boolean isCapital = city.isCapital();
String isCapitalName;
if(isCapital == null) {
isCapitalName = "";
} else if(isCapital) {
isCapitalName = "Capital";
} else {
isCapitalName = "City";
}
name = (city.getName() != null) ? city.getName() : "N/A";
name = ( (city.getName() == null)? "N/A" : city.getName() );
먼저 상태 (city.getName() == null)
가 점검됩니다. 그렇다면 "N/A"
name에 할당되거나 단순히 name="N/A"
또는 from의 값 city.getName()
이 name에 할당됩니다 (예 :) name=city.getName()
.
여기서 살펴볼 것들 :
- 조건은 괄호 안에 있고 물음표가옵니다. 그게 내가 쓰는 이유
(city.getName() == null)?
입니다. 여기서 물음표는 조건 바로 뒤에 있습니다. 보고 / 읽기 / 추측하기도 쉽습니다! - 콜론의 왼쪽 값 (
:
) 및 콜론의 오른쪽 값 (a) 조건이 true이면 콜론의 왼쪽 값이 지정되고, 그렇지 않으면 콜론의 오른쪽 값이 변수에 지정됩니다.
여기 참조가 있습니다 : http://www.cafeaulait.org/course/week2/43.html
여기 한 줄의 코드가 있습니다
name = (city.getName() != null) ? city.getName() : "N/A";
here is example how it work, run below code in js file and understand the result. This ("Data" != null)
is condition as we do in normal if()
and "Data"
is statement when this condition became true. this " : "
act as else and "N/A"
is statement for else condition. Hope this help you to understand the logic.
name = ("Data" != null) ? "Data" : "N/A";
console.log(name);
Use org.apache.commons.lang3.StringUtils:
name = StringUtils.defaultString(city.getName(), "N/A");
Simple & clear:
String manType = hasMoney() ? "rich" : "poor";
long version:
String manType;
if (hasMoney()) {
manType = "rich";
} else {
manType = "poor";
}
or how I'm using it to be clear for other code readers:
String manType = "poor";
if (hasMoney())
manType = "rich";
You can remove brackets and line breaks.
if (city.getName() != null) name = city.getName(); else name = "N/A";
You can use ?: operators in java.
Syntax:
Variable = Condition ? BlockTrue : BlockElse;
So in your code you can do like this:
name = city.getName() == null ? "N/A" : city.getName();
Assign condition result for Boolean
boolean hasName = city.getName() != null;
EXTRA: for curious
In some languages based in JAVA
like Groovy
, you can use this syntax:
name = city.getName() ?: "N/A";
You can do this in Groovy
because if you ask for this condition:
if (city.getName()) {
//returns true if city.getName() != null
} else {
//returns false if city.getName() == null
}
So the operator ?:
assign the value returned from the condition. In this case, the value of city.getName()
if it's not null
.
You can use ternary operator in java.
Syntax:
Condition ? Block 1 : Block 2
So in your code you can do like this,
name = ((city.getName() == null) ? "N/A" : city.getName());
For more info you can refer this resource.
name = city.getName()!=null?city.getName():"N/A"
참고URL : https://stackoverflow.com/questions/8898590/short-form-for-java-if-statement
'Programing' 카테고리의 다른 글
TypeScript의 공개 정적 const (0) | 2020.05.25 |
---|---|
JavaScript 코드를 사용하여 브라우저 너비를 얻는 방법은 무엇입니까? (0) | 2020.05.25 |
Vim이 ~ 확장자를 가진 파일을 저장하는 이유는 무엇입니까? (0) | 2020.05.25 |
UIImage를 NSData로 변환 (0) | 2020.05.25 |
python smtplib을 사용하여 여러 수신자에게 이메일을 보내는 방법은 무엇입니까? (0) | 2020.05.25 |