package scannerex;
import java.util.Scanner;
public class Dong {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("숫자 입력 : ");
int a = sc.nextInt();
System.out.println("글자 입력 : ");
String str = sc.nextLine();
}
}

nextLine()에 사용자가 문자열을 입력하기도 전에 끝나는 이유는 뭘까?
처음에 nextInt()에 숫자를 입력하고 엔터를 치게 되는데 만약 7을 치고 엔터를 쳤다 했을 때 '7\n' 가 입력 받게 된다.
nextInt()는 숫자만 읽기 때문에 7을 읽고 출력해주고 우리가 엔터로 쳐서 입력된 \n은 남게 된다.
남은 \n은 nextLine()에 가게 된다.
nextLine()이 라인을 읽어봐도 문자열이 없어 빈 문자열을 출력하고 바로 nextLine()이 종료되며 우리가 입력하기도 전에 끝나는 것이었다.
- 해결안
package scannerex;
import java.util.Scanner;
public class Dong {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("숫자 입력 : ");
int a = sc.nextInt();
sc.nextLine(); //추가 부분
System.out.println("글자 입력 : ");
String str = sc.nextLine();
}
}

nextInt() 다음에 바로 nextLine() 으로 \n을 한번 빼주거나 next()를 사용한다.
'오류, 기능, 문제해결(JAVA)' 카테고리의 다른 글
| 2차원 배열 연습 (3) | 2024.12.27 |
|---|---|
| scanner에서 무한 while 중단 조건 간략화 (0) | 2024.12.27 |
| 두 개의 정수를 입력 받으면, 두 정수 사이의 값을 출력(scanner 연습) (0) | 2024.12.27 |
| 문자열의 길이 추출 length() / length. length(), size() 차이 (0) | 2024.12.23 |
| 두 수를 나누는데 소수점을 활용해야함 (0) | 2024.12.23 |