Java/Java icia 8일차

메소드를 이용해 유틸리티 만들기

swkn 2023. 3. 3. 14:53

숫자만 입력받아야 할때가 있을때 사용할 수 있는 유틸리티 코드 만들기

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;
	}

}