숫자만 입력받아야 할때가 있을때 사용할 수 있는 유틸리티 코드 만들기
public class Util {
// 숫자 체크 메소드
public int numberCheck() {
int result;
Scanner sc = new Scanner(System.in);
while (true) {
if (sc.hasNextInt()) { // 입력한 값이 숫자면
result = sc.nextInt();
break;
} else {
System.out.print("숫자만 입력>");
sc.nextLine();
}
}
return result; // 입력한 값을 result에 저장
}
매개변수를 입력받아 사용할수도 있다
이러면 장점은 여러곳에서 원하는 변수를 넣어 재사용이 가능
public int numberCheck1(String str) {
int result;
Scanner sc = new Scanner(System.in);
while (true) {
if (sc.hasNextInt()) { // 입력한 값이 숫자면
result = sc.nextInt();
break;
} else {
System.out.print(str+"는 숫자만 입력>");
sc.nextLine();
}
}
return result; // 입력한 값을 result에 저장
}
몇자 이내로 입력받고 싶을때도 응용 할수 있다.
//str는 i자 이내 체크 함수
public String lengthCheck(String str, int i) {
Scanner sc= new Scanner(System.in);
String result = sc.next();
while(true) {
if(result.length()<i) {
break;
}else {
System.out.println(str+"(은)는 "+i+"자리 이내로 입력해주세요");
result = sc.next();
}
}
return result;
}
}'Java > Java icia 8일차' 카테고리의 다른 글
| 유틸리티 메소드 (0) | 2023.03.03 |
|---|---|
| 로그인시스템 배운것들 추가해서 프로그램만들기 (0) | 2023.03.03 |
| 멤버시스템 만들기( 필드,생성자,메소드를 이용) (0) | 2023.03.03 |
| for문의 향상된,개선된 for문 (0) | 2023.03.03 |
| ArrayList (0) | 2023.03.03 |