\n: 줄바꿈
이름을 넣을 때
System.out.print("이름을 입력하세요 : "); //
String name = sc.nextLine();
1) "최다원\n" 치면 버퍼(buffer)라고 하는 임시 메모리 공간에 저장됨
2) "최다원\n"이라는 데이터는 nextLine으로 이동
3) buffer는 공란이 됨
4) "최다원\n"은 변수 name에 대입되면서 \n이 빠지게 됨
나이를 넣을 때
System.out.print("나이를 입력하세요 : ");
int age = sc.nextInt();
1) nextLine 빼고 전부 다, buffer에 \n 을 남기고 데이터만 가져감
2) buffer에 \n이 남게 됨
3) 그 다음 nextLine 데이터에 자동으로 \n이 넘어감
4) 그러나 \n은 데이터 취급하지 않기 때문에 nextLine은 아무 데이터 없이 string으로 바로 들어감
※버퍼를 비우지 않을 경우, 버퍼에 \n이 남아있기 때문에 nextLine은 데이터가 있다고 인지해서 /n을 가져가버림
그럼 어떻게 해결해야 할까?
int age = sc.nextInt();
System.out.print("주소를 입력하세요 : ");
String address = sc.next();
int age = sc.nextInt();
sc.nextLine(); // 위치 확인!!
System.out.print("주소를 입력하세요 : ");
String address = sc.nextLine();
String strAge = sc.nextLine();
int age = Integer.parseInt(strAge); // 파싱 작업
System.out.print("주소를 입력하세요 : ");
String address = sc.nextLine();
-Char 한 글자 출력 방법
1) 문자열로 받아오기
2) 한 글자만 추출
System.out.print("성별을 입력하세요 (M/F) : ");
String strGender = sc.nextLine();
strGender.charAt(0); // 0부터 수를 세는 컴퓨터의 특성, zero base