연산자
산술연산자 : +, , *, /, %(나머지), <<, >>
비교연산자 : >, <, >=, <=, ==, !=
논리 연산자 : &&, ||, !
대입연산자 : =, ++, --
기타연산자 : (type), ? : , instance of
연산자 우선순위 : 산술 > 비교 > 논리 > 대입
if 조건문
if (조건) {
// true인 경우
결과값
}else{
// false인 경우
결과값
}
scanner
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
// A에게 값 입력받기
System.out.println("A 입력: ");
String aHand = sc.nextLine();
}
두 개의 값을 비교하는 메서드 → Objects.equals(좌, 우) : 좌우가 같은 경우 true, 다른 경우 false
package week02;
import java.util.Objects;
import java.util.Scanner;
public class w08 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// A에게 값 입력받기
System.out.println("A 입력: ");
String aHand = sc.nextLine();
System.out.println("B 입력: ");
String bHand = sc.nextLine();
// 두개의 값을 비교하는 메서드 -> Objects.equals(좌, 우) : 좌 우가 같은 경우 true, 다른 경우 false
if (Objects.equals(aHand, "가위")) {
if (Objects.equals(bHand, "가위")) {
System.out.println("A와 B는 비겼습니다.");
} else if (Objects.equals(bHand, "바위")) {
System.out.println("B가 이겼습니다.");
} else if (Objects.equals(bHand, "보")) {
System.out.println("A가 이겼습니다.");
} else {
System.out.println("B가 이상한 값을 입력했습니다.");
}
} else if (Objects.equals(aHand, "바위")) {
if (Objects.equals(bHand, "가위")) {
System.out.println("A가 이겼습니다.");
} else if (Objects.equals(bHand, "바위")) {
System.out.println("A와 B는 비겼습니다.");
} else if (Objects.equals(bHand, "보")) {
System.out.println("B가 이겼습니다.");
} else {
System.out.println("B가 이상한 값을 입력했습니다.");
}
} else if (Objects.equals(aHand, "보")) {
if (Objects.equals(bHand, "가위")) {
System.out.println("B가 이겼습니다.");
} else if (Objects.equals(bHand, "바위")) {
System.out.println("A가 이겼습니다.");
} else if (Objects.equals(bHand, "보")) {
System.out.println("A와 B는 비겼습니다.");
} else {
System.out.println("B가 이상한 값을 입력했습니다.");
}
}else {
System.out.println("A가 이상한 값을 입력했습니다.");
}
}
}
for문
package week02;
public class w09 {
public static void main(String[] args) {
// for문
// (초기값 ; 조건문 ; 증가연산)
for (int i = 0; i < 4; i++){
System.out.println(i + " 번째 출력!");
}
// 향상된 for문
// 기존 : for문 안에 3개의 표현이 들어감
// 향상된 for문 : 2개로 줄여줌
int [] numbers = {3, 6, 9, 12, 15};
for (int number: numbers){
System.out.print(number + "");
}
}
}
배열(정적배열)
package week02.array;
public class Arr01 {
public static void main(String[] args) {
// 배열 생성
int[] intArray = new int[3]; //{0,0,0}
boolean[] boolArray = new boolean[3]; ///{false, false, false}
String[] stringArray = new String[3]; //{"", "", ""}
//배열 선언 먼저! -> 나중에 초기화
int[] intArray2;
intArray2 = new int[3]; // {0, 0, 0}
// 생성한 배열을 '순회' -> 배열의 값을 하나씩 뽑아서 조회
// (1) 단건 조회
System.out.println(intArray[1]);
System.out.println("----------------");
// (2) 다건 조회(important!)
// length : 길이를 구하는 메서드
for (int i=0; i<intArray2.length; i++){
System.out.println(intArray2[i]);
}
}
}
package week02.array;
import java.util.Arrays;
public class Arr02 {
public static void main(String[] args) {
// 초기화
// 1. 배열에 특정값 대입해서 선언
int[] intArr = {1, 2, 3, 4, 5};
String[] stringArray = {"a", "b", "c", "d"};
// 2. for문을 통해서 대입
for(int i=0; i<intArr.length; i++){
intArr[i] = i;
}
System.out.println("---------------------");
// 다건 출력
for (int i=0; i<intArr.length; i++){
System.out.println(intArr[i]);
}
int[] intArr2 = {10, 20, 30, 40, 50};
for(int i: intArr2){
System.out.println(i);
}
//배열의 주소를 모두 같은 값으로 초기화
Arrays.fill(intArr2, 1);
for (int item: intArr2){
System.out.println(item);
}
}
}
배열 복사
package week02.array;
import java.util.Arrays;
public class w03 {
public static void main(String[] args) {
// 2. Arrays.copyOf() 메서드
int[] a = {1, 2, 3, 4 };
int[] b = Arrays.copyOf(a, a.length); //배열과 함께 length도 같이 넣어줍니다.
a[3] = 0;
System.out.println(a[3]);
System.out.println(b[3]);
}
}
결과값:// a와 b는 완전히 다른배열
0
4
문자 vs 문자열
문자(char / 1byte), 문자열(String)
String = char[]
[기본형 변수 vs 참조형 변수]
char < String(훨씬 더 많이 씀!)
package week02.array;
public class Arr04 {
public static void main(String[] args) {
String str = "ABCD";
// (1) length
int strLength = str.length();
System.out.println(strLength); //4
// (2) charAt(int index)
char strChar = str.charAt(1);
System.out.println(strChar); //B
// (3) substring(int fromIdx, int toIdx)
String strSub = str.substring(0, 3);
System.out.println(strSub); //ABC
// (4) equals(String str)
String newStr = "ABCD";
boolean strEqual = newStr.equals(str);
System.out.println(strEqual); //true
// (5) toCharArray() : String -> char[]
char[] strCharArray = str.toCharArray();
// (6) 반대로 char[] -> String -> char
char[] charArray = {'A', 'B', 'C'};
String charArrayString = new String(charArray);
System.out.println(charArrayString); //ABC
}
}
가변배열
package week02.array;
public class Arr05 {
public static void main(String[] args) {
//가변배열
int[][] array = new int[3][];
//배열 원소마다 각기 다른 크기로 지정
array[0] = new int[2];
array[1] = new int[4];
array[2] = new int[1];
//중괄호로 초기화를 아예 해버릴 때도 가능!
int [][ ] array2 = {
{10, 20},
{10, 20 , 30, 40},
{10}
};
}
}
컬렉션
배열보다 다수의 참조형 데이터를 더 쉽고 효과적으로 처리할 수 있는 기능을 가지고 있다.
컬렉션 기능 : 크기 자동조정/ 추가/ 수정/ 삭제/ 반복/ 순환/ 필터/ 포함확인 등
컬렉션 종류
List(동적배열) : 순서가 있는 데이터의 집합(데이터 중복 허용) - 배열과 비슷Set: 순서가 없는 데이터의 집합 (데이터 중복 허용 안함) - 순서없고 중복없는 배열Queue : 빨대처럼 한쪽에서 데이터를 넣고 반대쪽에서 데이터를 뺄 수 있는 집합(FIFO)Map : 순서가 없는 (key, value)쌍으로 이루어진 데이터의 집합 (key값 중복 허용 안함)ArrayList
ArrayList → 동적배열
처음에 길이를 몰라도 만들 수 있음!
package week02.collection;
import java.util.ArrayList;
public class Col1 {
public static void main(String[] args) {
// List(ArrayList, 동적배열)
// 처음에 길이를 몰라도 만들 수 있음!
ArrayList<Integer> intList = new ArrayList<Integer>(); //선언 + 생성
intList.add(99);
intList.add(15);
intList.add(3);
System.out.println(intList.get(1)); //15
// 2번째 있는 값(15)을 바꿔보자.
intList.set(1, 10); // list 1번 값을 10으로 바꾸자
System.out.println(intList.get(1)); //10
// 삭제
intList.remove(0);
System.out.println(intList.get(0)); //10
System.out.println("클리어 전");
System.out.println(intList.toString()); //[10, 3]
intList.clear();
System.out.println("클리어 후");
System.out.println(intList.toString()); //[]
}
}
Linked List
stack
수직으로 값을 쌓아놓고, 넣었다가 뺀다 FIFO(Basket)
push, peek, pop
최근 저장된 데이터를 나열하고 싶거나, 데이터의 중복 처리를 막고 싶을 때 사용
package week02.collection;
import java.util.Stack;
public class Col2 {
public static void main(String[] args) {
Stack<Integer> intStack = new Stack<Integer>(); //선언 및 생성
intStack.push(10);
intStack.push(15);
intStack.push(11);
//다 지워질 대 까지 출력
while(!intStack.isEmpty()){
System.out.println(intStack.pop());
} // 11, 15, 10(역순으로)
// 다시 추가
intStack.push(10);
intStack.push(15);
intStack.push(11);
//peak
System.out.println(intStack.peek()); //11
System.out.println(intStack.size()); //3
}
}
Queue : FIFO
add, peek, poll
생성자가 없는 인터페이스
package week02.collection;
import java.util.LinkedList;
import java.util.Queue;
public class Col3 {
public static void main(String[] args) {
// Queue : 생성자가 없는 인터페이스
Queue<Integer> intQueue = new LinkedList<>(); //선언 및 생성
intQueue.add(1);
intQueue.add(5);
intQueue.add(9);
//다 지워질 대 까지 출력
while(!intQueue.isEmpty()){
System.out.println(intQueue.poll());
} // 1, 5, 9
// 다시 추가
intQueue.add(1);
intQueue.add(5);
intQueue.add(9);
intQueue.add(10);
//peak
System.out.println(intQueue.peek()); //1
System.out.println(intQueue.size()); //4
}
}
Set
순서 없고, 중복 없음!
순서가 보장되지 않는 대신 중복을 허용하지 앟도록 하는 프로그램에서 사용할 수 있는 자료구조
Set → 그냥 쓸 수도 있음. 그러나, HashSet, TreeSet 등으로 응용해서 같이 사용 가능
Set은 생성자가 없는 껍데기라서 바로 생성할 수 없음!!
생성자가 존재하는 HashSet을 이용해서 Set을 구현해 볼 수 있음!
package week02.collection;
import java.util.HashSet;
import java.util.Set;
public class Col4 {
public static void main(String[] args) {
Set<Integer> intSet = new HashSet<>(); //선언 및 생성
intSet.add(1);
intSet.add(12);
intSet.add(5);
intSet.add(9);
intSet.add(1);
intSet.add(12);
for (Integer value: intSet){
System.out.println(value);
} // 1, 5, 9, 12
//contains
System.out.println(intSet.contains(2)); //false
System.out.println(intSet.contains(5)); //true
}
}
Map
key - value pair
key라는 값으로 unique하게 보장이 돼야 함!
Map → HashMap, TreeMap으로 응용
package week02.collection;
import java.util.HashMap;
import java.util.Map;
public class Col5 {
public static void main(String[] args) {
Map<String, Integer> intMap = new HashMap<>();
//키 값
intMap.put("일", 11);
intMap.put("이", 12);
intMap.put("삼", 13);
intMap.put("삼", 14); // 중복 key
intMap.put("삼", 15); // 중복 key
//key 값 전체 출력(향상된 for문)
for (String key: intMap.keySet()) {
System.out.println(key);
} // 이, 일, 삼
//value 값 전체 출력(향상된 for문)
for (Integer value: intMap.values()){
System.out.println(value);
} // 12, 11, 15
System.out.println(intMap.get("삼")); //15
}
}