On the first line, printString:followed by the unalteredStringread from stdin.
On the second line, printDouble:followed by the unaltereddoubleread from stdin.
On the third line, printInt:followed by the unalteredintegerread from stdin.
To make the problem easier, a portion of the code is already provided in the editor.
Note:If you use thenextLine()method immediately following thenextInt()method, recall thatnextInt()reads integer tokens; because of this, the last newline character for that line of integer input is still queued in the input buffer and the nextnextLine()will be reading the remainder of the integer line (which is empty).
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
// Write your code here.
System.out.println("String: " + s);
System.out.println("Double: " + d);
System.out.println("Int: " + i);
}
}
○ 문제의 핵심
- scan.nextInt() 동작 이후 scan.nextLine() 진행시 개행문자 '\n' 이 개행문자로 남아 다음 본문을 재대로 인식하지 못한 부분을 해결
○ 해결방법
1. int, double도 scan.nextLine()으로 입력받은 후 Integer.parseInt(String); Double.parseDouble(String); 으로 변경
(BUT, 해당 문제는 최초에 Write your Code here 전 int i 를 받고 있어 다음 문장을 작성해야하므로 Integer.parseInt(String) 를 사용할 수 없음)
2. 숫자 먼저 받은 후(int, Double) String을 받기전 scan.nextLine(); 으로 개행문자 제거
다음 scan.nextLine(); 을 이용해 정상적인 문자열 scan 진행
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
// Write your code here.
double d = scan.nextDouble();
scan.nextLine();
String s = scan.nextLine();
System.out.println("String: " + s);
System.out.println("Double: " + d);
System.out.println("Int: " + i);
}
}