public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int a, b;
a = scanner.nextInt();
b = scanner.nextInt();
System.out.println(a + b);
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int sum = 0;
while(scanner.hasNextInt()) {
sum += scanner.nextInt();
}
System.out.println(sum);
}
}
<입력>
1
hello
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
scanner.nextLine();
String s = scanner.nextLine();
System.out.println(n + "\n" + s);
}
}
Scanner는 매우 편리하지만 속도가 느리기 때문에, 입력을 많이 받아야 하는 경우에는 BufferedReader를 사용하는 것이 훨씬 좋다.
bufferedReader에서는 read와 readLine만 있기 때문에, 정수는 파싱을 해야한다.
<입력>
10 20 30 40
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
String[] line = bf.readLine().split(" ");
String a = line[0] + line[1];
String b = line[2] + line[3];
long result = Long.valueOf(a) + Long.valueOf(b);
System.out.println(result);
}
}
<입력>
1 2 3 4 5
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
String line = bf.readLine();
StringTokenizer st = new StringTokenizer(line, " ");
int sum = 0;
while(st.hasMoreTokens())
sum += Integer.valueOf(st.nextToken());
System.out.println(sum);
}
}
<입력>
10,20,30,40,50
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
String line = bf.readLine();
StringTokenizer st = new StringTokenizer(line, ",");
int sum = 0;
while(st.hasMoreTokens())
sum += Integer.valueOf(st.nextToken());
System.out.println(sum);
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
for (int i = 1; i <= a; i++)
System.out.println(i);
}
}
수행시간 : 676 MS, 메모리 : 30256 KB
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= a; i++)
sb.append(i + "\n");
System.out.println(sb);
}
}
수행시간 : 216 MS, 메모리 : 11532 KB