// 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);
}
}
rand.nextInt(45)
--> 0 이상 45 미만의 난수를 반환int num = rand.nextInt(45) + 1
--> 1부터 45 사이의 난수를 반환isDuplicate = true;
--> 중복isDuplicate = false;
--> 중복ximport 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_출력
}
}
"JavaScript Object Notation"의 약자로, 경량의 데이터 교환 형식이다.
JSON은 프로그래밍 언어
나 플랫폼
에 관계 없이데이터를 교환할 수 있도록 설계 되었다.
JSON은 키-값 쌍(key-value pair)
으로 이루어진 데이터 객체를 표현한다.
// 표현식 예시)
{ "name" : "John", "age" : 30 }
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};
}
}
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}
}
}