ex1) Call by Reference, Call by Value
public class Money {
private int value;
public Money(int value) {
this.value = value;
}
}
public class Main {
public static void main(String[] args) {
Money money1 = new Money(500);
Money money2 = new Money(500);
System.out.println(money1 == money2);
System.out.println(money1.equals(money2));
}
}
위의 코드에서 출력값 중 true가 하나는 나올법한데 전부 false가 나온다. 왜 그런걸까? 이유를 정리해보자.
money1와 money2는 다른 object이다.
ex2) equals(), hashCode()
import java.util.Objects;
public class Money {
private int value;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Money money = (Money) o;
return value == money.value;
}
@Override
public int hashCode() {
return Objects.hash(value);
}
public Money(int value) {
this.value = value;
}
}
mission
문자 말고 숫자만 입력하라구!
import static java.lang.Integer.parseInt;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean isContinued = true;
while (isContinued) {
System.out.println("숫자를 입력해주세요.");
String input = scanner.nextLine();
try {
int number = parseInt(input);
System.out.println("입력하신 숫자는 " + number + "입니다.");
}
catch (NumberFormatException e) {
System.out.println("잘못된 값을 입력하셨습니다.");
}
}
}
}
휴대폰 번호 입력받기
public class PhoneNumber {
private String value;
public PhoneNumber(String value) {
this.validate(value);
this.value = value;
}
private void validate(String phoneNumber) {
String input010 = "^(010)-\\d{4}-\\d{4}$";
String input11 = "^\\d{3}\\d{4}\\d{4}$";
if (!phoneNumber.matches(input010)) {
if (!phoneNumber.matches(input11)) {
throw new IllegalArgumentException(("휴대폰 번호는 11글자여야 합니다."));
}
throw new IllegalArgumentException("휴대폰 번호는 010으로 시작해야 합니다.");
}
}
public String getPhoneNumberFormally() {
String regEx = "(\\d{3})(\\d{3,4})(\\d{4})";
return this.value.replace(regEx, "$1-$2-$3");
}
}
Q.정규표현식이 잘못된 것 같은데 뭐가 틀렸는지 잘모르겠어요..
안녕하세요 수현님! 혹시 제 코드 참고해보시고 코드 수정 한 번해보세요~!! 제 코드 중에 이해 안 되시는 부분 있으시면 언제든 연락 남겨주시구요:) 멋사 지원도 잘 준비하시구요!!!!!! 화이팅입니다~~~