1. 입출력

 

10869 사칙연산

https://www.acmicpc.net/problem/10869

 

10869번: 사칙연산

두 자연수 A와 B가 주어진다. 이때, A+B, A-B, A*B, A/B(몫), A%B(나머지)를 출력하는 프로그램을 작성하시오. 

www.acmicpc.net

import java.util.Scanner;

public class Main {

 

public static void main(String[] args) {

//Scanner 객체 생성

Scanner sc = new Scanner(System.in);

 

//각 변수에 띄어쓰기 기준으로 입력 값을 저장한다.

int a = sc.nextInt();

int b = sc.nextInt();

 

//변수를 활용하여 연산값을 출력한다.

System.out.println(a + b);

System.out.println(a - b);

System.out.println(a * b);

System.out.println(a / b);

System.out.print(a % b);

}

 

}

백준에서는 클래스 이름을 Main으로 변경해야 올바르게 채점된다.

입력을 위해 Scanner객체를 사용하여 사용자의 입력을 받고 변수에 저장하여 해당 연산을 수행 후 출력하였다.



2588 곱셈

https://www.acmicpc.net/problem/2588

 

2588번: 곱셈

첫째 줄부터 넷째 줄까지 차례대로 (3), (4), (5), (6)에 들어갈 값을 출력한다.

www.acmicpc.net

import java.util.Scanner;

public class Main {

 

public static void main(String[] args) {

//Scanner 객체 생성

Scanner sc = new Scanner(System.in);

//입력을 받아 두 변수에 저장

int result1 = sc.nextInt();

int result2 = sc.nextInt();

 

//result2에 각 자리수를 다른 변수에 저장

int digit1 = result2 % 10;

int digit2 = (result2 % 100) / 10;

int digit3 = result2 / 100;

 

//result1를 result2의 각 자리수마다 곱한다.

int result3 = result1 * digit1;

int result4 = result1 * digit2;

int result5 = result1 * digit3;

int result6 = result1 * result2;

 

//해당 값을 출력

System.out.println(result3);

System.out.println(result4);

System.out.println(result5);

System.out.println(result6);

}

 

}

 

 

2. 조건문

14681 사분면 고르기

https://www.acmicpc.net/problem/14681

 

14681번: 사분면 고르기

점 (x, y)의 사분면 번호(1, 2, 3, 4 중 하나)를 출력한다.

www.acmicpc.net

import java.util.Scanner;

public class Main {

 

public static void main(String[] args) {

//Scanner 객체 생성

Scanner sc = new Scanner(System.in);

//입력을 각 변수에 저장

int x = sc.nextInt();

int y = sc.nextInt();

 

//만약 x값이 양수, y값도 양수면 1사분면

if (x > 0 && y > 0) {

System.out.println("1");

}

//만약 x값이 음수, y값도 양수면 2사분면

else if (x < 0 && y > 0) {

System.out.println("2");

}

//만약 x값이 음수, y값도 음수면 3사분

else if (x < 0 && y < 0) {

System.out.println("3");

}

//만약 x값이 양수, y값도 음수면 4사분

else if (x > 0 && y < 0) {

System.out.println("4");

}

}

 

}

&&연산자를 통해 두 조건이 만족하면 해당 문자열을 출력하도록 코드를 작성했다.



2884  알람 시계

https://www.acmicpc.net/problem/2884

 

2884번: 알람 시계

상근이는 매일 아침 알람을 듣고 일어난다. 알람을 듣고 바로 일어나면 다행이겠지만, 항상 조금만 더 자려는 마음 때문에 매일 학교를 지각하고 있다. 상근이는 모든 방법을 동원해보았지만,

www.acmicpc.net

import java.util.Scanner;

public class Main {

 

public static void main(String[] args) {

//Scanner 객체 생성

Scanner sc = new Scanner(System.in);

//입력을 각 변수에 저장

int hour = sc.nextInt();

int min = sc.nextInt();

 

//만약 분이 45보다 작다면 시간을 -1, 45분에서 min을 뺀 후 60에서 한번 더 뺄셈.

if (min - 45 < 0) {

//0시에서 1시간을 빼면 23시간이 되므로.

if (hour - 1 < 0) {

hour = 23;

min = 60 - (45 - min);

} //일반적인 경우는 hour에서 1을 빼주면 된다.

else {

hour -= 1;

min = 60 - (45 - min);

}

} //min이 45분보다 크다면

else {

min -= 45; //45분을 빼도 시간이 변하지 않으므로 hour는 추가 연산이 필요없다.

}

System.out.printf("%d %d", hour, min);

}

 

}

 


3. 반복문

8393 합

https://www.acmicpc.net/problem/8393

 

8393번: 합

n이 주어졌을 때, 1부터 n까지 합을 구하는 프로그램을 작성하시오.

www.acmicpc.net

import java.util.Scanner;

//main 클래스 선언

public class Main {

//n을 배개변수로 받는 메소드 작성

public int result(int n) {

//n이 1보다 작거나 같다면 n을 반환

//해당 조건을 통해 종료 조건을 설정했다.

if (n <= 1) {

return n;

}

//n이 1보다 크다면 n에 n-1의 값을 호출하는 과정을 반복

//종료조건에 충족할 때까지 반복하며 최종 값을 반환한다.

else {

return n + result(n - 1);

}

 

}

 

public static void main(String[] args) {

//해당 객체 생성

Scanner sc = new Scanner(System.in);

Main main = new Main();

//입력을 각 변수에 저장

int n = sc.nextInt();

//포멧팅을 통해 해당 클래스의 반환값을 출력한다.

System.out.printf("%d", main.result(n));

}

 

}

 

 

10952 A + B - 5

https://www.acmicpc.net/problem/10952

 

10952번: A+B - 5

두 정수 A와 B를 입력받은 다음, A+B를 출력하는 프로그램을 작성하시오.

www.acmicpc.net

import java.util.Scanner;

 

public class Main {

public static void main(String[] args) {

//해당 객체 생성

Scanner sc = new Scanner(System.in);

//0 0을 입력하면 루프가 끝나게 반복문을 설정

while (true) {

int A = sc.nextInt();

int B = sc.nextInt();

 

if (A == 0 && B == 0) {

break;

}

else {

System.out.println(A + B);

}

}

}

 

}

 


4. 1차원 배열

 

10807 개수 세기

https://www.acmicpc.net/problem/10807

 

10807번: 개수 세기

첫째 줄에 정수의 개수 N(1 ≤ N ≤ 100)이 주어진다. 둘째 줄에는 정수가 공백으로 구분되어져있다. 셋째 줄에는 찾으려고 하는 정수 v가 주어진다. 입력으로 주어지는 정수와 v는 -100보다 크거

www.acmicpc.net

import java.util.Scanner;

 

public class Main {

public static void main(String[] args) {

//해당 객체 생성

Scanner sc = new Scanner(System.in);

//글자 수를 세기위해 count변수 생성

int count = 0;

 

//N을 입력받고 N개의 값을 저장할 배열을 선언하였다.

//배열은 자동으로 0으로 초기화 된다.

int N = sc.nextInt();

int[] array = new int[N];

 

//반복문을 통해 입력값을 배열에 저장하였다.

//nextInt()는 기본적으로 공백을 포함하여 입력값을 분리한다.

for (int i = 0; i < N; i++) {

array[i] = sc.nextInt();

}

 

//찾을 숫자 V를 입력받는다.

int V = sc.nextInt();

//반복문을 통해 V가 배열에 들어있다면 count를 1씩 증감시켰다.

for (int j = 0; j < N; j++) {

if (array[j] == V) {

count += 1;

}

else {

continue;

}

}

System.out.println(count); //11

//1 4 1 2 4 2 4 2 3 4 4

//5

//출력값 : 0

}

 

}

 

 

1546 평균

https://www.acmicpc.net/problem/1546

 

1546번: 평균

첫째 줄에 시험 본 과목의 개수 N이 주어진다. 이 값은 1000보다 작거나 같다. 둘째 줄에 세준이의 현재 성적이 주어진다. 이 값은 100보다 작거나 같은 음이 아닌 정수이고, 적어도 하나의 값은 0보

www.acmicpc.net

import java.util.Scanner;

 

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

 

int largest_array = 0; //배열에서 가장 큰 값을 저장할 변수

double sum = 0; //배열의 값들을 모두 더해 저장할 변수

 

int answer = sc.nextInt();

sc.nextLine();

 

//배열 생성

int[] array = new int[answer]; //원 점수를 저장한 배열

double[] f_array = new double[answer]; //조작 점수를 저장한 배열

 

for (int i = 0; i < answer; i++) {

array[i] = sc.nextInt();

if (array[i] > largest_array) {

largest_array = array[i]; // 최댓값 업데이트

}

}

 

for (int k = 0; k < answer; k++) {

//원 점수에 가장 큰 점수를 나누고 100을 곱한 수 조작점수 배열에 저장

f_array[k] = (double)array[k] / largest_array * 100;

//조작점수의 평균을 내기 위해 해당 변수에 조작점수의 합을 저장

sum += f_array[k];

}

//조작점수의 평균을 출력

System.out.println(sum / answer);

}

 

 

 

}

 

 

5. 문자열

 

27866 문자와 문자열

https://www.acmicpc.net/problem/27866

 

27866번: 문자와 문자열

첫째 줄에 영어 소문자와 대문자로만 이루어진 단어 $S$가 주어진다. 단어의 길이는 최대 $1\,000$이다. 둘째 줄에 정수 $i$가 주어진다. ($1 \le i \le \left|S\right|$)

www.acmicpc.net

import java.util.Scanner;

 

public class Main {

public static void main(String[] args) {

//객체 생성

Scanner sc = new Scanner(System.in);

//사용자에게 입력받은 단어 저장

String word = sc.nextLine();

//split 함수를 사용해서 한글자 단위로 끊어서 배열에 저장

String[] array = word.split("");

 

//출력할 인덱스 값 입력 및 저장

int index = sc.nextInt();

sc.nextLine();

//해당 인덱스값 출력

System.out.println(array[index - 1]);

}

}

 

 

11718 그대로 출력하기

https://www.acmicpc.net/problem/11718

 

11718번: 그대로 출력하기

입력이 주어진다. 입력은 최대 100줄로 이루어져 있고, 알파벳 소문자, 대문자, 공백, 숫자로만 이루어져 있다. 각 줄은 100글자를 넘지 않으며, 빈 줄은 주어지지 않는다. 또, 각 줄은 공백으로 시

www.acmicpc.net

import java.util.Scanner;

 

public class Main {

public static void main(String[] args) {

//객체 생성

Scanner sc = new Scanner(System.in);

//hasNext를 조건으로 루프

while (sc.hasNext()) {

//해당 입력받은 문자열을 그대로 출력

String word = sc.nextLine();

System.out.println(word);

}

}

}

 

해당 문제를 풀기 위해선 EOF의 개념을 알아야 한다.

EOF란 End Of File의 약자로 "더이상 읽을 수 있는 데이터가 없음" 을 나타내는 용어이다.

주로 백준 문제에서 몇개의 입력을 받을 지 모르는 상황에 사용한다.

 

자바에서 Scanner를 사용할 때 hasNext() 메소드를 사용하면 된다.

만약 입력이 있으면 true, 입력이 없다면 false를 반환하는 해당 메소드를 통해 EOF를 처리할 수 있다.

'JAVA > SOUP' 카테고리의 다른 글

[JAVA / SOUP] 클래스와 인스턴스 그리고 객체  (0) 2024.04.04
[JAVA / SOUP] 입력과 출력  (1) 2024.04.04
[JAVA / SOUP] 메소드  (1) 2024.04.03