JAVA/05_입력받기

next() 와 nextLine()의 차이

Y_____527 2021. 1. 14. 23:15
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
//===================Stribg input method=> next() vs nextLine()===================
package ex01.input;
 
import java.util.Scanner;
 
//next() vs nextLine() <--- String input method
//String(문자열)을 입력받는 방법2가지-.next() / .nextLine()
public class Ex03_InputTestEx {
    public static void main(String[] args) {
        
        Scanner sc = new Scanner(System.in); //Ctrl + Shift + O -> 자동import
        System.out.println("string input: ");
        String s1 = sc.next();  //1)next(): 공백을 인식하지 못함 
        
        System.out.println("string input: ");
        String s2 = sc.nextLine(); //2)nextLine(): 공백을 인식함
        
        System.out.println("next()로 입력 받은 문자열: " + s1);
        System.out.println("nextLine()으로 입력 받은 문자열: " + s2);
        
        
        System.out.println("문자열은 결합됨: " + s1 + s2);
        
        System.out.println(Integer.parseInt(s1) + Integer.parseInt(s2));
        //숫자를 써도 next()를 이용하면 문자로 인식해서 문자처럼 결합되어 나오기 때문에,
        //Integer.parseInt메소드를 이용해서 정수형태로 바꿔주면 숫자로 인식되어 더한값이 나옴
        
        
    }
 
}
 
cs

1) System.out.println("string input: ");

   String s1 = sc.next(); 

                  =>next(); 공백을 인식하지 못함

 

2) String s2 = sc.nextLine(); 

                  =>nextLine(); 공백을 인식함


cf) System.out.println(Integer.parseInt(s1) + Integer.parseInt(s2));

        ->숫자를 써도 next()를 이용하면 문자로 인식해서 문자처럼 결합되어 나오기 때문에,

        ->Integer.parseInt메소드를 이용해서 정수형태로 바꿔주면 숫자로 인식되어 정수더한값이 나옴