public class MaxValue {
// 세 개의 정수 a,b,c 중 최대값을 구하여 반환하는 메소드
public static int max(int a, int b, int c) {
int max = (a > b) ? a : b;
max = (b > c) ? b : c;
return max;
}
// main
public static void main(String[] args) {
System.out.println("최대값 : " + max(5, 3, 6));
}
}
Scanner 클래스는 java.util 패키지에 포함되어 있으며, 다양한 형태의 입력(문자열, 정수, 실수 등)을 처리할 수 있다.import java.util.Scanner;
public class InputExample {
public static void main(String[] args) {
// Scanner 객체 생성
Scanner scanner = new Scanner(System.in);
// 사용자로부터 정수 입력받기
System.out.print("정수를 입력하세요: ");
int number = scanner.nextInt();
// 입력 버퍼 비우기 (줄바꿈 문자 제거)
scanner.nextLine();
// 사용자로부터 문자열 입력받기
System.out.print("문자열을 입력하세요: ");
String text = scanner.nextLine();
// 입력받은 정수와 문자열 출력
System.out.println("입력받은 정수: " + number);
System.out.println("입력받은 문자열: " + text);
// Scanner 객체 닫기
scanner.close();
}
}
nextInt() : 정수 (int) 타입의 데이터를 읽어들인다.
-2,147,483,648 에서 2,147,483,647 까지 ( -2^31 에서 2^31 - 1 )nextLong() : 긴 정수 (long) 타입의 데이터를 읽어들인다.
-9,223,372,036,854,775,808 에서 9,223,372,036,854,775,807 까지-2^63 에서 2^63 - 1 )nextFloat() : 부동 소수점 (float) 타입의 데이터를 읽어들인다.
-3.4028235E+38 에서 3.4028235E+38 까지nextDouble() : 더블 정밀도의 부동 소수점 (double) 타입의 데이터를 읽어들인다.
-1.7976931348623157E+308 에서 1.7976931348623157E+308 까지nextBoolean() : 불리언 (boolean) 타입의 데이터를 읽어들인다.
true 또는 false 문자열에 대해 대소문자를 구분하지 않는다.nextByte() : 바이트 (byte) 타입의 데이터를 읽어들인다.
-128 에서 127 까지 ( -2^7 에서 2^7 - 1 )nextShort() : 짧은 정수 (short) 타입의 데이터를 읽어들인다.
-32,768 에서 32,767 까지 ( -2^15 에서 2^15 - 1 )next() : 다음 토큰을 문자열로 읽어들인다.
nextLine() : 줄의 끝까지 문자열을 읽어들인다.
void 를 사용한다.return 키워드를 사용하여 결과값을 반환한다.접근제한자 <static> 반환타입 메서드명(매개변수) {..구현..}public static int max(int x, int y) {
if (x > y) {
return x;
} else {
return y;
}
}
public static void main(String[] args) {
int a = 10;
int b = 20;
int maxValue = max(a, b);
System.out.println("최대값: " + maxValue);
}
a 와 b 를 비교하여, a 가 더 큰 경우 b 와 c 를 비교한다. b 가 더 크면 b 가 중앙값이다. 아니면 a 와 c 를 비교하여 더 작은 값이 중앙값이 된다.
// 3개의 정숫값을 입력하고 중앙값을 구하여 출력
import java.util.Scanner;
public class Median {
static int med3(int a, int b, int c) {
if (a >= b)
if (b >= c)
return b;
else if (a <= c)
return a;
else
return c;
else if (a > c)
return a;
else if (b > c)
return c;
else
return b;
}
public static void main(String[] args) {
Scanner stdIn = new Scanner(System.in);
System.out.println("세 정수의 중앙값을 구합니다.");
System.out.print("a 값 : ");
int a = stdIn.nextInt();
System.out.print("b 값 : ");
int b = stdIn.nextInt();
System.out.print("c 값 : ");
int c = stdIn.nextInt();
System.out.println("중앙값은 " + med3(a, b, c) + "입니다.");
}
}
조건문을 통해 프로그램의 로직을 세분화하고, 사용자의 입력이나 계산 결과에 따라 다르게 반응하도록 설계할 수 있다.
연산자와 피연산자
+ , - , * , / , %== , != , < , > , <= , >=&& , || , != , += , -= , *= , /=++ , --? : (조건식 ? 값1 : 값2)& , | , ^ , ~ , << , >>




import java.util.Scanner;
class SumWhile {
public static void main(String[] args) {
Scanner stdIn = new Scanner(System.in);
System.out.println("1부터 n까지의 합을 구합니다.");
System.out.print("n값: ");
int n = stdIn.nextInt();
int sum = 0; // 합
int i = 1;
while (i <= n) { // i가 n 이하면 반복
sum += i; // sum에 i를 더함
i++; // i 값을 1 증가(increment)
}
System.out.println("1부터 " + n + "까지의 합은 " + sum + "입니다.");
}
}
import java.util.Scanner;
public class SumEven {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n, sum = 0;
System.out.print("정수 n을 입력하세요 : ");
n = sc.nextInt();
for (int i = 1; i <= n; i++) {
if (i % 2 == 0)
sum += i;
}
System.out.println("n까지의 짝수의 합 : " + sum);
}
}
import java.util.Scanner;
public class Sum3Drainage {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n, sum = 0;
System.out.print("정수 n을 입력하세요 : ");
n = sc.nextInt();
for (int i = 1; i <= n; i++) {
if (i % 3 == 0)
sum += i;
}
System.out.println("n까지의 3의 배수의 합 : " + sum);
}
}
import java.util.Scanner;
public class TwoDigits {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n;
System.out.println("두자리 양의 정수를 입력해주세요.");
do {
System.out.print("정수값 입력 : ");
n = sc.nextInt();
} while (n < 10 || n > 99);
System.out.println("입력한 숫자는 " + n + "입니다.");
}
}
&& , || , ! , ^public class Multi99Table {
public static void main(String[] args) {
System.out.println("------- 구구단 곱셈표 -------");
for (int i = 1; i < 10; i++) {
for (int j = 1; j < 10; j++) {
System.out.printf("%d * %d =%2d ", i, j, i * j);
}
System.out.println();
}
}
}
import java.util.Scanner;
public class TriangleLB {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n;
do {
System.out.print("직각 이등변 삼각형의 단 수를 입력해주세요 : ");
n = sc.nextInt();
} while (n <= 0);
for (int i = 0; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
import java.util.Scanner;
public class TriangleLB2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n;
do {
System.out.print("이등변삼각형의 단 수를 입력해주세요 : ");
n = sc.nextInt();
} while (n <= 0);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - i; j++)
System.out.print(" ");
for (int j = 0; j < (i*2+1); j++)
System.out.print("*");
System.out.println();
}
}
}
toString(): 배열의 내용을 문자열로 변환하여 반환 . 주로 디버깅 목적으로 사용sort(): 배열을 정렬. 기본적으로는 오름차순으로 정렬, 오브젝트 배열의 경우에는 해당 객체들이 구현한 Comparable 인터페이스의 compareTo() 메서드에 따라 정렬.binarySearch(): 지정된 값의 위치를 찾음. 이 메서드를 사용하기 전에 배열이 반드시 정렬되어 있어야 함.copyOf(): 지정된 길이로 배열을 복사.copyOfRange(): 배열의 지정된 범위를 복사.fill(): 배열의 모든 요소를 지정된 값으로 설정.equals(): 두 배열이 같은지 비교.asList(): 배열을 고정 크기의 리스트로 변환.import java.util.Arrays;
public class DuplicateArray {
public static void main(String[] args) {
int[] original = {10, 20, 30, 40, 50};
int[] copied = original.clone(); // copied는 original의 복제본을 참조
copied[2] = 0; // copied 배열의 세 번째 요소를 0으로 변경
System.out.println("original = " + Arrays.toString(original));
System.out.println("copied = " + Arrays.toString(copied));
}
}
/* 실행결과
original = [10, 20, 30, 40, 50]
copied = [10, 20, 0, 40, 50]
*/
import java.util.Scanner;
public class MaxOfScores {
static int maxOf(int[] scores) {
int max = Integer.MIN_VALUE;
for (int i = 0; i < scores.length; i++) {
if (scores[i] > max)
max = scores[i];
}
return max;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("학생 수 입력 : ");
int n = sc.nextInt();
int[] scores = new int[n];
for (int i = 0; i < n; i++) {
System.out.print((i + 1) + "번째 점수 입력 : ");
scores[i] = sc.nextInt();
}
System.out.println("최댓값 : " + maxOf(scores));
}
}
import java.util.Random;
import java.util.Scanner;
public class MaxOfWeightsRand {
static int maxOf(int[] weights) {
int max = weights[0];
for (int i = 1; i < weights.length; i++)
if (weights[i] > max)
max = weights[i];
return max;
}
public static void main(String[] args) {
Random rand = new Random();
Scanner sc = new Scanner(System.in);
System.out.println("몸무게의 최댓값을 구합니다.");
System.out.print("사람 수: ");
int num = sc.nextInt(); // 입력받은 사람 수로 배열의 크기를 결정
int[] weights = new int[num]; // 사람 수만큼 몸무게를 저장할 배열 생성
for (int i = 0; i < num; i++) {
weights[i] = 40 + rand.nextInt(60); // 몸무게를 40kg에서 100kg 사이의 난수로 결정
System.out.println("weights[" + i + "] : " + weights[i]);
}
System.out.println("최댓값은 " + maxOf(weights) + "입니다.");
}
}
.nextInt() : -2,147,483,648 ~ 2,147,483,647 사이의 값 (min ~ max).nextInt(60) : 0~60 의 난수// 사용자로부터 입력받은 값으로 구성된 배열을 역순으로 정렬
import java.util.Arrays;
import java.util.Scanner;
class InvertArray {
//--- 배열 요소 a[idx1]과 a[idx2]의 값을 교환 ---//
static void swap(int[] a, int idx1, int idx2) {
int temp = a[idx1];
a[idx1] = a[idx2];
a[idx2] = temp;
}
//--- 배열 a의 요소를 역순으로 정렬 ---//
static void reverse(int[] a) {
for (int i = 0; i < a.length / 2; i++)
swap(a, i, a.length - i - 1);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("점수의 개수: ");
int num = sc.nextInt(); // 점수의 개수를 입력받음
int[] scores = new int[num]; // 점수를 저장할 배열 생성
for (int i = 0; i < num; i++) {
System.out.print("scores[" + i + "] : ");
scores[i] = sc.nextInt(); // 점수 입력
}
reverse(scores); // 배열 scores의 요소를 역순으로 정렬
System.out.println("점수를 역순으로 정렬했습니다.");
System.out.println("scores = " + Arrays.toString(scores));
}
}
public class CompareArrays {
static boolean areArraysEqual(int[] arr1, int[] arr2) {
if (arr1.length != arr2.length)
return false;
for (int i = 0; i < arr1.length; i++) {
if (arr1[i] != arr2[i])
return false;
}
return true;
}
public static void main(String[] args) {
// 테스트를 위한 두 배열 선언
int[] array1 = {1, 2, 3, 4, 5};
int[] array2 = {1, 2, 3, 4, 5};
int[] array3 = {1, 2, 3, 4};
// areArraysEqual 메소드를 사용하여 배열 비교
System.out.println("array1과 array2는 동일한가? " + areArraysEqual(array1, array2));
System.out.println("array1과 array3는 동일한가? " + areArraysEqual(array1, array3));
}
}
public class DecimalToBinaryExam {
public static void main(String[] args) {
int decimal = 29;
StringBuilder binary = new StringBuilder();
while (decimal > 0) {
binary.append(decimal % 2);
decimal /= 2;
}
System.out.println(binary.reverse().toString());
}
}
: 문자열을 동적으로 조작하고 수정하는 데 사용됨.
: 문자열의 변경이 필요한 상황
StringBuilder sb = new StringBuilder();
// 문자열 추가
sb.append("Hello");
// 문자열 삽입
sb.insert(5, " ");
// 문자열 수정
sb.replace(6, 10, "World");
// 문자열 삭제
sb.delete(5, 6);
// 문자열 출력
System.out.println(sb.toString()); // 출력 결과: HelloWorld