쯔이's Dev

자바 기초(3) - Scanner, 출력메소드 본문

JAVA/기초

자바 기초(3) - Scanner, 출력메소드

jjhim531 2024. 7. 8. 01:01
반응형

<Scanner>

사용자로부터 입력되는 정수, 실수, 문자열을 처리하는 Class.

* import  작성   

import java.util.Scanner;

 - 단축키 : Scanner 생성 후 ctrl + shift + o를 눌러준다.

 

* Scanner 생성   

 Scanner sc = new Scanner(System.in);

 

<키보드 입력 값 받기>

* sc.next~();  방식

ex) sc.nextInt();     sc.nextDouble();      sc.next();    .........

1. sc.next()

  • 설명:
    • 공백 또는 탭(\t) 이전까지의 입력을 가져옵니다.
    • 공백, 탭, 개행 문자를 구분자로 사용합니다.
    • 사용자가 입력한 값 중 첫 번째 단어만 반환.
    • 띄어쓰기 입력불가 - 띄어쓰기를 구분인자로 생각하여 각각의 변수에 저장.(  줄구분은 저장하지 않음)

따라서 입력 후에 엔터키를 치면 엔터키가 다음 sc.next~();의 입력값으로 인식된다.

이걸 방지하기 위해  sc.nextLine();을 한번 써주고 엔터키를 처리해준다.

Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = sc.next(); // "Hello World" 입력 시 "Hello"만 반환
System.out.println("Input: " + input);

>>  출력

Enter a string: Hello World
Input: Hello

 

2. sc.nextLine()

  • 설명:
    • 한 줄 전체를 입력받습니다.
    • 줄바꿈 문자(\n)를 기준으로 입력을 구분하며, 줄바꿈 문자를 제외한 값을 반환한다
    • 사용자가 입력한 값중 \n(개행문자)를 포함하는 한 라인을 읽고 \n버린 나머지 값만 가져온다.
    • 문자열에 띄어쓰기 입력가능, 줄구분까지 저장.

 

Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = sc.nextLine(); // "Hello World" 입력 시 전체 반환
System.out.println("Input: " + input);

>> 출력

Enter a string: Hello World
Input: Hello World

 

3. sc.nextInt(),   sc.nextFloat() 등  숫자 입력 메소드

  • 설명:
    • 숫자 입력을 받는 메소드.
    • int, double, float, long 등 각 데이터 타입에 맞는 값을 반환한다.
    • 주의: 입력 후 줄바꿈 문자(\n)가 남아 있기 때문에, 이후 sc.nextLine()을 사용하면 빈 값을 반환하거나 문제가 생길 수 있다.
Scanner sc = new Scanner(System.in);
System.out.print("Enter an integer: ");
int number = sc.nextInt(); // 숫자를 입력받음

System.out.print("Enter a string: ");
String input = sc.nextLine(); // 줄바꿈 문자 때문에 빈 문자열 반환
System.out.println("Input: " + input);

>> 출력

Enter an integer: 42
Enter a string:
Input:

해결 방법:

  • 숫자 입력 후 sc.nextLine()을 호출해 줄바꿈 문자를 비워줍니다.
Scanner sc = new Scanner(System.in);
System.out.print("Enter an integer: ");
int number = sc.nextInt();

sc.nextLine(); // 줄바꿈 문자 제거

System.out.print("Enter a string: ");
String input = sc.nextLine();
System.out.println("Input: " + input);

>> 출력

Enter an integer: 42
Enter a string: Hello World
Input: Hello World

 

4. sc.close()

  • 설명:
    • Scanner를 더 이상 사용하지 않을 때 호출하여 자원을 해제.
    • 프로그램이 종료되기 전 호출하지 않아도 큰 문제가 없지만, 자원을 효율적으로 관리하려면 호출하는 것이 좋다.

 

Scanner sc = new Scanner(System.in);
System.out.println("Enter a value:");
String value = sc.nextLine();

sc.close(); // Scanner 종료

System.out.println("You entered: " + value);

 

 

정리

  • sc.next(): 공백 이전의 첫 번째 단어만 가져옴.
  • sc.nextLine(): 한 줄 전체를 가져옴.
  • 숫자 입력 메소드 (sc.nextInt() 등): 줄바꿈 문자 처리 주의.
  • sc.close(): 사용 후 자원 해제.
  • 특히 숫자 입력 후 줄바꿈 문자를 처리하는 코드를 추가하는 습관을 들이는 것이 좋다.

 

<출력 메소드>

* System.out.print();

줄바꿈 없이 ()의 변수, 문자, 숫자, 논리값을 모니터에 출력해주는 메소드

* System.out.println();

()의 내용을 출력 후 자동으로 줄바꿈을 해주는 메소드

* System.out.printf();

서식이 있는 출력
⇒ 지시를 통해 변수의 값을 여러가지 형식으로 바꿔서 출력할 수 있다.
⇒ System.out.printf("출력 서식", 출력할 내용);

728x90
반응형

'JAVA > 기초' 카테고리의 다른 글

변수명이 같을 때  (0) 2024.09.11
접근지정자  (0) 2024.07.14
변수의 종류  (0) 2024.07.13
자바 기초(2) - 변수, 상수, 선언, 초기화  (0) 2024.07.07
JAVA 기초 (1) - 프로그래밍 순서, 주석  (0) 2024.07.06