Java
화면에서 입력받기 - Scanner
성장코딩
2022. 12. 20. 22:47
< 소스 코드 >
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
package sample03;
import java.util.Scanner; //Scanner class를 사용하기 위해 추가
public class MainClass2 {
public static void main(String[] args) {
// input(입력) - console
Scanner sc = new Scanner(System.in); // Scanner class 객체를 생성
// boolean
boolean b; // 입력할 데이터를 보관할 변수
System.out.print("b = "); // 입력할 데이터를 명시
b = sc.nextBoolean(); // 입력 받음
System.out.println("b: " + b); // 입력한 결과를 출력
// integer
int number;
System.out.print("number = ");
number = sc.nextInt();
System.out.println("number: " + number);
// double
double d;
System.out.print("d = ");
d = sc.nextDouble();
System.out.println("d: " + d);
// string
String str;
System.out.print("str = ");
str = sc.next();
// 주의! next()는 space를 못받아들여서 hello world 치면 hello만 출력
System.out.println("str: " + str);
}
}
|
cs |
< Console >

Theme. next()와 nextLine()의 차이
- next(): 공백 또는 줄 바꿈까지만 읽는다. (한 단어만 읽을 수 있음)
- nextLine(): 한 줄 전체를 읽는다(문장을 다 읽을 수 있음)
즉, 다음과 같은 차이가 있다.
"Hello Java World"라고 입력했을 때,
1. next()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
package sample03;
import java.util.Scanner;
public class MainClass2 {
public static void main(String[] args) {
// input(입력) - console
Scanner sc = new Scanner(System.in);
// string
String str;
System.out.print("str = ");
str = sc.next();
System.out.println("str: " + str);
}
}
|
cs |
< console >

2. nextLine()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
package sample03;
import java.util.Scanner;
public class MainClass2 {
public static void main(String[] args) {
// input(입력) - console
Scanner sc = new Scanner(System.in);
// string
String str;
System.out.print("str = ");
str = sc.nextLine();
System.out.println("str: " + str);
}
}
|
cs |
< console >
