API 기초

강9·2023년 12월 15일
0

Java

목록 보기
65/71

🔖 직접 만들어 사용하는 class 예시

- Utility


📌 배열에 저장된 수 중에서 최대값과 최소값을 구하는 클래스 만들기

  • 최소값 초기화 : int min - arr[0];
  • 최대값 초기화 : int max - arr[0];
  • 배열에서 첫번째 값을 최대, 최소값으로 초기화한다.
  • 만약 최대값을 찾는데 초기화를 임의로 0으로 했다고 가정했을 때, 배열의 값이 1~3까지의 3개의 정수로 이루어 져 있을 경우 초기화한 0보다 모두 크기 때문에 정확한 값이 나오지 않을 수 있기 때문에 초기화는 배열의 첫번째 값으로 고정하여 비교한다.
// Utility 예시)

public class MinMaxFinder {
    
    // 최소값 구하기
    public static int findMin(int[] arr) {
        int min = arr[0];
        for (int i = 0; i < arr.length; i++) {
            if(arr[i] < min) {
                min = arr[i];
            } // if_
        } // for_
        return min;
    } // findMin_end

    // 최대값 구하기
    public static int findMax(int[] arr) {
        int max = arr[0];
        for (int i = 0; i < arr.length; i++) {
            if(arr[i] > max) {
                max = arr[i];
            } // if_
        } // for_
        return max;
    } // findMin_end
}
// Utility 활용 예시)

import fc.java.Course2.model2.MinMaxFinder;

public class MinMaxFinderTest {
    public static void main(String[] args) {
        int[] arr = {5,1,6,2,8};

        int min = MinMaxFinder.findMin(arr);
        int max = MinMaxFinder.findMax(arr);
        System.out.println("min : " + min);
        System.out.println("max : " + max);
    }
}

🔖 java에서 제공해주는 class 예시

📌 java Random 클래스를 이용한 6개의 난수를 생성하여 중복되지 않도록 배열에 저장하기

  • rand.nextInt(45) --> 0 이상 45 미만의 난수를 반환
  • int num = rand.nextInt(45) + 1 --> 1부터 45 사이의 난수를 반환
  • isDuplicate = true; --> 중복
  • isDuplicate = false; --> 중복x
import java.util.Random;

public class RandomAPI {
    public static void main(String[] args) {
        Random rand = new Random();

        int[] arr = new int[6];
        int i = 0; // 저장위치(pos)

        while(i < 6) {
            int num = rand.nextInt(45)+1; // 1~45
            boolean isDuplicate = false;

            for (int j = 0; j < i; j++) {
                if (arr[j] == num) {
                    isDuplicate = true;
                    break;
                } // if_
            } // for_
            if (!isDuplicate) {
                arr[i++] = num;
            } // if_
        } // while_
        
        // 출력
        for (int num : arr) {
            System.out.print(num+" ");
        } // for_end_출력
    }
}

🔖 다운받아서 사용하는 class 예시

📌 API 다운로드(MVN링크)

💡 JSON이란?

"JavaScript Object Notation"의 약자로, 경량의 데이터 교환 형식이다.
JSON은 프로그래밍 언어플랫폼관계 없이데이터를 교환할 수 있도록 설계 되었다.
JSON은 키-값 쌍(key-value pair)으로 이루어진 데이터 객체를 표현한다.

// 표현식 예시)

{ "name" : "John", "age" : 30 }

📌 Gson API를 활용하여 객체 다루기

1️⃣ 예제 1. 자바 객체를 JSON으로 변환하기

  • Person 클래스를 정의하고, 이 클래스의 객체를 JSON 형식으로 변환하여 출력한다.
  • Gson 객체를 생성한 후, toJson() 메서드를사용하여 객체를 JSON 형식의 문자열로 변환한다.

✓ 변환할 객체 : Person 변수명 = new Person클래스(변환할 내용);
✓ Gson 객체 생성 : Gson gson변수명 = new Gson();
✓ 변환 : String json변수명 = gson변수명.toJson(객체변수명);


/* public class Person {
    private String name;
    private int age;
    //...이하 생략
*/

import com.google.gson.Gson;

public class GsonToAPI {
    public static void main(String[] args) {
        Person person = new Person("John", 30);
        Gson gson = new Gson();
        String json = gson.toJson(person);
        System.out.println(json); // {"name" : "John", "age" : 30};
    }
}

2️⃣ 예제 2. JSON을 자바 객체로 변환하기

  • Gson 객체를 생성하고 fromJson() 메서드를 사용하여 JSON 문자열을 자바 객체로 변환한다.
  • 변환할 클래스의 타입을 인자로 전달한다.

✓ 변환할 내용 : String json변수명 = {\"객체1\" : \"내용1\", \"객체2\" : \"내용2\"};
-> 문자열의 경우 내부 "" 앞에 꼭 \를 붙여줘야함
✓ Gson 객체 생성 : Gson gson변수명 = new Gson();
✓ 변환 : Person 변수명 = gson변수명.fromJson(json, Person.class);


/* public class Person {
    private String name;
    private int age;
    //...이하 생략
*/

import com.google.gson.Gson;

public class GsonFromAPI {
    public static void main(String[] args) {
        String json = "{\"name\" : \"John\", \"age\" : 30}"; // \넣어야 에러나지 않음(내부 "") --> JSON -> Person
        Gson gson = new Gson();
        Person p = gson.fromJson(json, Person.class);
        System.out.println(p.getName()); // John
        System.out.println(p.getAge()); // 30
        System.out.println(p.toString()); // Person{name='John', age=30}
    }
}
profile
코린이 일기

0개의 댓글