-
[백준] 1008번 : A/B - JAVA (자바)Algorithm 2023. 8. 11. 17:00
solved.ac 에서 클래스 1의 에센셜 첫 번째 문제이다.
주의할 것
* 입력이 공백 단위로 주어진다.
* 상대오차 또는 절대오차 범위 이하여야 한다.1. 익숙한 Scanner 풀이
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); double a = sc.nextDouble(); double b = sc.nextDouble(); sc.close(); System.out.println(a/b); } }
** 반드시 double 형 출력
import java.util.Scanner; public class main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); double a = sc.nextDouble(); double b = sc.nextDouble(); sc.close(); System.out.println(a/b); } }
2. BufferedReader 풀이
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.StringTokenizer; public class Main { public static void main ( String [] args ) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str = br.readLine(); StringTokenizer st = new StringTokenizer(str, " "); double a = Double.parseDouble(st.nextToken()); double b = Double.parseDouble(st.nextToken()); System.out.println(a/b); } } /* 굳이 String 변수 생성 안하고 입력과 동시에 구분자로 분리해줘도 된다. 그냥 str 변수 들어갈 자리에 바로 br.readLine() 입력해 나머지 그대로 작성 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()," "); double a = Double.parseDouble(st.nextToken()); double b = Double.parseDouble(st.nextToken()); System.out.println(a/b); */
자바의 입력 방법
1. Scanner
1) Scanner 클래스 import
import java.util.Scanner;스캐너 패키지는 java.util 패키지에 있기 때문에 java.util.Scanner;을 해주어야 한다.
java.util.*; 을 통해 util의 패키지의 모든 클래스를 import 할 수 있는데, 나중에 코드가 복잡해지면 어떤 클래스를 import 했는지 구분하기 어려워질 수 있어 import할 패키지만 쓰는 것을 추천한다.2) 객체를 생성한다.
Scanner sc = new Scanner(System.in);여기서 System.in 은 입력한 값을 Byte 단위로 읽는 것을 뜻한다. 객체명은 자유롭게 선언해주면 되는데
보통 객체명으로 in, scan, sc 를 쓴다.위와 같이 많이 쓰이는 객체명으로 해주는 것이 좋다. 기본 포맷을 따라가줘야 나중에 다른 사람이 읽더라도 한 번에 이해하기가 편하고, 상대방 또한 똑같은 입장이기에 특별한 상황이 아니라면 공개 소스에는 트렌드에 맞게 써주는 것이 좋다.
3) 입력을 받는다.
String a_space= sc.next();
String a_enter=sc.nextLine();
sc.nextBoolean 처럼 자료형에 맞 같은 형식으로 쓰고 받아주면 된다.
* sc.next() : 문자열 입력시 공백 전까지만 받음
* sc.nextLine() : 문자열 입력시 Enter 입력 전까지만 받음
상황에 맞게 선택하면 되는데, next()의 경우 에러가 발생할 수 있는 경우가 많아서
대부분 문제는 행 단위로 입력을 받으니 문자열 입력 형태로는 sc.nextLine()을 쓴다.2. BufferedReader
BufferdReader의 경우 문자열을 받는 대표적인 방법은 readLine()과 read()이다.
readLine()은 한 행을 읽고, read()는 한 문자만 읽어온다.이것 역시 특별한 경우가 없는 한 readLine()를 쓴다.
더보기주의할 것들 !
* 주의 1
read()의 경우 문자 한 개를 아스키코드(문자)로 읽어 정수형태로 반환한다.
예를 들어 0을 입력하면 실제 변수에는 48이 저장된다.그래서 문자를 받을 때 입력한 값 그대로 정수로 쓰고 싶다면 '0'또는 48을 빼주어야 원하는 값이 저장된다.
* 주의 2
공백도 문자다. read()는 사이에 공백이 있다면 그 공백을 문자로 읽어 변수에 저장한다.
따라서 공백으로 구분된 문자도 BufferedReader 를 쓸 때 readLine()으로 해야하는데, 이 문자열을 공백단위로 분리해줘야 문제를 풀 수 있다.
< 문자열 분리 방법 >1. StringTokenizer 클래스를 이용하여 분리해주는 방법 ( 성능면에서 더 좋음, 단순 규칙으로 문자열 분리해줄 때 )
import java.util.StringTokenizer 로 import 해준 다음 객체 생성을 해준다.객체 생성할 때 StringTokenizer("문자열", 구분자); 해주면 된다.
구분된 변수를 꺼낼 때는 차례대로 nextToken();을 해주면 문자열을 반환해준다.
이때 반환시킨 문자열을 반환됨과 동시에 해당 객체에서 사라지게 된다.그리고 문자열을 반환했으니 Integer.parseInt()를 통해 int형으로 변환시켜준다.아래는 st-lab.tistory 에 나온 예시// 방법 2-1 import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str = br.readLine(); StringTokenizer st = new StringTokenizer(str," "); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); System.out.println(a+b); /* 굳이 String 변수 생성 안하고 입력과 동시에 구분자로 분리해줘도 된다. BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()," "); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); System.out.println(a+b); */ } }
2. split()을 이용하는 방법split이 더 간단하지만, 나중에 문자열을 다루고 데이터 양이 많아지면 StringTokenizer 이 성능이 좋아 수행시간이 짧다.
따라서 문제를 풀 때 세 가지 방법이 있을 수 있다.
1. Scanner 사용
2. BufferedReader + split() 사용
3. BufferedReader + StringTokenizer 사용Scanner보다 BufferReader의 성능이 훨씬 좋다.
엄청나신 분이다.. 읽다가 시간이 없어서 덜 읽었는데, 마저 읽어봐야겠다.
'Algorithm' 카테고리의 다른 글
[백준] 2557번 : Hello World - JAVA (자바) (0) 2023.08.12 [백준] 2438번 : 별찍기 -1 - JAVA (자바) (0) 2023.08.11 [백준] 1330번 : 두 수 비교하기 - JAVA (자바) (0) 2023.08.11 구현 (0) 2022.10.14 그리디 (0) 2022.10.09