일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
- function
- DS
- MacOS
- Pipelining
- mysql
- DATAPATH
- DB
- computer
- Java
- html
- system
- web
- github
- while
- Class
- XML
- CSS
- Linux
- python
- DoM
- data structure
- Algorithm
- MIPS
- php
- control
- for
- architecture
- instruction
- react
- javascript
- Today
- Total
YYYEJI
[JAVA] Scanner 클래스 본문
Scanner class란?
User에게 값을 입력받는 클래스입니다.
↓↓↓ Scanner class의 method를 하나씩 살펴보겠습니다 ↓↓↓
우선 Scanner class를 사용할 때는 아래 패키지를 import 해야 됩니다.
import java.util.Scanner;
패키지를 improt해준 이후에는 object를 생성해줍니다.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
}
① next() & nextLine()
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s1 = scan.next();
System.out.println(s1);
}
next() method를 사용하게 되면 user가 아무리 문장을 입력해도 단어 하나만 받아옵니다.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s1 = scan.nextLine();
System.out.println(s1);
}
nextLine() method를 사용하면 user가 입력한 문장을 모두 변수에 저장하게 됩니다.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s1 = scan.next();
String s2 = scan.nextLine();
System.out.println(s1);
System.out.println(s2);
}
next()와 nextLine()을 사용하고 한 줄만 입력했을 때 nextLine()의 줄은 입력받지 않고
"abc" 이후의 문자들이 s2에 들어가게 됩니다.
② nextInt()
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
System.out.println(i);
}
nextInt()는 정수를 받는 method입니다.
③ nextDouble()
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
double d = scan.nextDouble();
System.out.println(d);
}
nextDouble()는 실수를 받는 method입니다.
④ nextFloat()
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
float f = scan.nextFloat();
System.out.println(f);
}
nextFloat()는 nextDouble()과 마찬가지고 실수를 받는 method입니다.
둘의 차이점은
nextDouble은 double 형의 변수를 받을 때, nextFloat는 float 형의 변수를 받을 때 사용합니다.
또한 double이 float보다 더 큰 범위의 값을 받고 싶을 때 사용하게 됩니다.
⑤ nextBoolean()
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
boolean isTrue = scan.nextBoolean();
System.out.println(isTrue);
}
nextBoolean()은 true/false 중 하나의 값을 입력받을 때 사용하는 method입니다.
◡̈
'Java' 카테고리의 다른 글
[JAVA] If 문이란? (0) | 2022.12.24 |
---|---|
[JAVA] Flow of Control (0) | 2022.12.24 |
[JAVA] 변수(variable)란? (0) | 2022.12.23 |
[JAVA] 이클립스 The selection cannot be launched, and there are no recent launches 오류 해결하기 (0) | 2022.11.03 |
[JAVA] 자바에서 주석(comment) 처리하는 방법 (0) | 2022.10.23 |