JAVA
Scanner class in Java(User input)
seoca
2018. 12. 18. 07:58
Scanner ClassMethods
Method | Type |
nextDouble() | double |
nextFloat() | float |
nextInt() | int |
nextLine() | String |
next() | next complete token |
*token: 자바를 구성하는 최소 단위(smallest elements)를 말한다. e.g) 변수, 키워드, 연산자 etc. 구분자(delimiter)에 의해 구분되어질 수 있음
What's the difference between nextLine() and next() ?
nextLine() reads the string including space but next() only reads till space.
HackerRank
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import java.util.Scanner; // Scanner 사용할때 꼭 불러줘야 public class Solution { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int i = scan.nextInt(); double d = scan.nextDouble(); /*next()와 nextLine() 혹은 nextInt()와 nextLine()을 같이 사용하게 되는 경우 next(), nextInt()의 개행문자가 버퍼에 남는 문제 발생.*/ scan.nextLine(); // nextLine을 사용해서 String받기전에 버퍼값을 없애줘야한다. String s = scan.nextLine(); System.out.println("String: " + s); System.out.println("Double: " + d); System.out.println("Int: " + i); } } | cs |
Result
1 2 3 | String: Welcome to HackerRank's Java tutorials! Double: 3.1415 Int: 42 | cs |
reference
Hackerrank (https://www.hackerrank.com/)
w3schools (www.w3schools.com)