JAVA - Scanner의 활용 예제 (2022-07-08)

2022. 7. 9. 21:143층 1구역 - 개발의 장/JAVA

나는 전 시간에 System. in .read ();와 Scanner를 알아봤었다.

System. in .read ();는 간단하게 아스키코드 값을 불러온다고 생각하고,

Scanner는 next와 nextLine을 통해 데이터를 불러오고, 둘의 차이를 알아봤다.

 

오늘은 Scanner의 활용에 대해 좀 더 알아보고자 한다.

 

1. nextInt();

nextInt는 정수형 데이터를 불러올 때, 사용한다.

이전 게시물 코드블럭 주석에도 썼지만

Scanner sc = new Scanner(System.in);

에서 Scanner는 자료형, 예약어

sc는 변수(input, output, num 등등 임의적으로 설정 가능한 것.)

new Scanner는 new로 메모리에 공간을 확보한 후, Scanner 클래스의 내용을 담는다.

package input;

import java.util.Scanner;

public class Ex4 {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		System.out.print("정수 입력 : ");
		int data = sc.nextInt();

		System.out.println("입력받은 데이터 : " + data);
		
		sc.close();
	}

}

결과

정수 입력 : 50
입력받은 데이터 : 50

 

2. nextFloat();, nextDouble();

nextFloat, nextDouble은 소수점을 나타내는 실수형 데이터를 불러올 때 사용한다.

package input;

import java.util.Scanner;

public class Ex5 {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		System.out.print("체중 : ");
		double weight = sc.nextDouble();
		
		System.out.print("키 : ");
		float height = sc.nextFloat();
		
		System.out.println("체중 : " + weight);
		System.out.println("키 : " + height);
		sc.close();
	}

}

결과

체중 : 65.5
키 : 163.5
체중 : 65.5
키 : 163.5

 

3. chatAt(i);

String 타입의 데이터(문자열)에서 특정 문자를 char 타입으로 변환할 때 사용하는 함수이다.

 

String sample = "abc";
char target = sample.charAt(0);

위처럼 String 변수에서 사용할 수 있으며,
charAt(i)
i 자리에는 int 형 변수를 넣어서 원하는 위치의 문자를 가져올 수 있다.

 

Scanner를 사용한 예시를 알아보자.

package input;

import java.util.Scanner;

public class Ex6 {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		System.out.print("문자 입력 : ");
		String data = sc.next();
		char charData = data.charAt(0);
		
		System.out.println("입력 받은 문자 출력 : " + charData);
		
		
		
	}

}

결과

문자 입력 : 안녕하세요
입력 받은 문자 출력 : 안

 

4. 퀴즈예시

어떤 사람의 이름과 국어, 영어, 수학 점수를 입력하고 출력해 보자.

 

당신의 이름은 무엇입니까? : 홍길동
홍길동님의 국어 점수 : 100
홍길동님의 영어 점수 : 95
홍길동님의 수학 점수 : 80
==============
이름 : 홍길동
==============
국어 : 100
영어 : 95
수학 : 80
==============
합계 : 275
==============

 

 

package input;

import java.util.Scanner;

public class Quiz3 {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		System.out.print("당신의 이름은 무엇입니까? : ");
		String name = sc.next();
		
		System.out.print(name + "님의 국어 점수 : ");
		int kor = sc.nextInt();
		System.out.print(name + "님의 영어 점수 : ");
		int eng = sc.nextInt();
		System.out.print(name + "님의 수학 점수 : ");
		int math = sc.nextInt();
		
		System.out.println("==============");
		System.out.println("이름 : " + name );
		System.out.println("==============");
		System.out.println("국어 : " + kor);
		System.out.println("영어 : " + eng);
		System.out.println("수학 : " + math);
		System.out.println("==============");
		System.out.println("합계 : " + (kor+eng+math));
		System.out.println("==============");
		
		sc.close();
	}

}