본문 바로가기

자바/클래스

Scanner 클래스

예제1)


import java.util.Scanner;


/*

 * Scanner 

 *     단락문자의 패턴을 사용하여 입력을 토근에 따라

 *    분할하며 기본 토근은 공백이다.

 *    예외처리를 명시하지 않아도 된다.

 */

public class Test5 {

public static void main(String[] args) {

String name;

int k, e;

Scanner sc=new Scanner(System.in);


/*

System.out.print("이름?");

name=sc.next();

System.out.print("국어?");

k=sc.nextInt();

System.out.print("영어?");

e=sc.nextInt();

*/

/*

// 홍길동  80  60

System.out.print("이름 국어 영어(공백으로 구분) ? ");

name=sc.next();

k=sc.nextInt();

e=sc.nextInt();

*/

// 홍길동,50,60

System.out.print("이름,국어,영어(,으로 구분) ? ");

sc=new Scanner(sc.next()).useDelimiter("\\s*,\\s*");

name=sc.next();

k=sc.nextInt();

e=sc.nextInt();

sc.close();

System.out.println("이름:"+name);

System.out.println("총점:"+(k+e));

}

}


// 주황색 부분을 파랑색과 초록색 부분으로 주석을 제거하고 적용하면 여러가지 방법으로 입력받을 수 있는 것을 확인할 수 있다.


에졔1 결과) 이름과 점수를 입력 형태에 맞게 입력하면 이름과 총점을 계산하여 출력.

이름,국어,영어(,으로 구분) ? 홍길동,90,67
이름:홍길동
총점:157

============================================================================================================

예제2)

import java.util.Scanner;

public class Test6 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.print("이름 ? ");
String name=sc.nextLine(); // 중간에 공백도 입력 가능
System.out.print("나이 ? ");
int age=sc.nextInt();
sc.nextLine(); // 버퍼의 엔터를 버림
// sc.skip("[\\r\\n]+"); // 이경우는 뒤의 모든 엔터를 버리므로 처리가 제대로 되지 않음
System.out.print("생년월일 ? ");
String birth=sc.nextLine();
System.out.print("전화번호 ? ");
String tel=sc.nextLine();
System.out.println("이름 : " + name);
System.out.println("나이 : " + age);
System.out.println("생년월일 : " + birth);
System.out.println("전화 : " + tel);

sc.close();
}
}

예제2 결과)

이름 ? 홍길동
나이 ? 20
생년월일 ? 2011111
전화번호 ? 02111111111
이름 : 홍길동
나이 : 20
생년월일 : 2011111
전화 : 02111111111

'자바 > 클래스' 카테고리의 다른 글

abstract 클래스  (0) 2013.05.21
상속 super  (0) 2013.05.21
SimpleDateFormat  (0) 2013.05.19
Wrapper 클래스  (0) 2013.05.19
BigDecimal와 BigInteger  (0) 2013.05.19