Scanner 클래스
발행: (2026년 2월 20일 오후 10:53 GMT+9)
2 분 소요
원문: Dev.to
Source: Dev.to
Class in Java
Java에서 클래스 개념에 대한 정의.
Why Scanner?
Scanner 클래스는 키보드와 같은 다양한 소스에서 입력을 읽는 작업을 간소화합니다.
How to Use Scanner
Step 1: Import the package
import java.util.Scanner;
Step 2: Create a Scanner object
Scanner sc = new Scanner(System.in);
System.in → 키보드로부터 입력을 받습니다.
Step 3: Take input
int age = sc.nextInt();
String name = sc.nextLine();
double salary = sc.nextDouble();
Important Concept
다음과 같이 작성하면:
int age = sc.nextInt();
이후의 nextLine()이 건너뛰어질 수 있습니다. 이는 nextInt()가 줄 바꿈 문자를 소비하지 않기 때문입니다.
Correct way
int age = sc.nextInt();
sc.nextLine(); // 남아있는 줄 바꿈 문자를 소비
String name = sc.nextLine();
Common Scanner Methods
nextInt()– 정수를 읽음nextLine()– 한 줄의 텍스트를 읽음nextDouble()– 실수를 읽음
Always Close Scanner
sc.close();
Example
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Tamil mark:");
int tamil = sc.nextInt();
System.out.println("Enter English mark:");
int english = sc.nextInt();
System.out.println("Enter Maths mark:");
int maths = sc.nextInt();
System.out.println("Enter Science mark:");
int science = sc.nextInt();
System.out.println("Enter Social mark:");
int social = sc.nextInt();
sc.nextLine(); // 줄 바꿈 문자 소비
System.out.println("Student name:");
String name = sc.nextLine();
int total = tamil + english + maths + science + social;
System.out.println("Total Marks: " + total);
System.out.println("Student name: " + name);
sc.close(); // 좋은 습관
}
}