Today I Learned
연산자 우선순위 : 산술 > 비교 > 논리 > 대입
- 연산자 여러개가 함께 있는 연산을 계산할 때는 우선순위가 있음.
- 위 우선순위에 따라 최종 응답값 결정.
- 괄호로 감쌌을 때에는 괄호가 우선함.
연산 전에 피연산자의 타입을 일치시킴
표현 범위가 가장 큰 변수 타입으로 일치됨
ex) int a와 short b를 더하면 int 값으로, double의 경우 무엇을 더해도 double의 값으로 변환됨
byte를 8등분한게 bit
bit는 0, 1 둘 중 하나의 값만을 저장하는 컴퓨터가 저장 가능한 가장 작은 단위
따라서 bit 연산이 가장 빠름
bit의 자리수를 옮기는 것을 비트연산이라고 함
"<<" : 자리수를 왼쪽으로 옮기는 횟수만큼 2배의 배수로 곱셈이 연산
">>" : 자리수를 오른쪽으로 옮기는 횟수만큼 2의 배수로 나눗셈이 연산
ex) 1010(10) -> 0101(5)
package week02;
import java.util.Objects;
import java.util.Scanner;
public class w13 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// A에게 값 입력받기
System.out.println("A 입력 : ");
String aHand = sc.nextLine();
// B에게 값 입력받기
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와 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와 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 {
System.out.println("A님, 잘못된 값이 입력되었습니다.");
}
}
}
💡 if와 switch의 차이
if문은 복합조건을 지원, switch는 피연산자 한 개에 대한 조건만 지원.
if문은 상대적으로 코드 중복이 많음, switch는 코드중복이 적음.
Scanner sc = new Scanner(System.in);
int passNum = sc.nextInt(); // 출력제외할 구구단수 값
for (int i = 2; i <= 9; i++) {
if (i == passNum) {
continue;
}
for (int j = 2; j <= 9; j++) {
System.out.println(i + "곱하기" + j + "는" + (i * j) + "입니다.");
}
}
인덱스를 가지며, 이 인덱스에 의해 접근이 가능한 순차적으로 구성된 자료구조.
한 번에 많은 양의 데이터를 다룰 때 사용.
✔️ 선언 방법
1️⃣타입
[]
변수
; 👉int[] intArray;
2️⃣타입
변수[]
; 👉int intArray[];
✔️ 생성 방법
new
타입
[]
👉int[] intArray = new int[3];
// 배열 생성
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]);
// (2) 다건 조회
// length : 길이를 구하는 메서드
for (int i = 0; i < intArray2.length; i++) {
System.out.println(intArray2[i]);
}
// 1. 배열에 특정값 대입해서 선언
int[] intArr = {1, 2, 3, 4, 5};
String[] stringArr = {"a", "b", "c", "d"};
// 2. for문을 통해서 대입
for (int i = 0; i < intArr.length; i++) {
intArr[i] = i;
}
// 3. Arrays.fill : 배열의 주소를 모두 같은 값으로 초기화
Arrays.fill(intArr, 1);
// 얕은 복사 : 주소값만 복사, b값 수정시 a값도 수정됨
int[] a = {1, 2, 3, 4};
int[] b = a;
int[] c = {1, 2, 3, 4};
int[] d = new int[a.length];
// 깊은 복사 : 실제 값을 가지고 있는 배열의 기본형 값을 꺼내서 복사
for (int i = 0; i < c.length; i++) {
d[i] = c[i];
}
// 1. clone() 메서드
int[] e = {1, 2, 3, 4};
int[] f = e.clone(); // 가장 간단한 방법, but 2차원 이상 배열에서는 얕은 복사로 동작
// 2. Arrays.copyOf() method
int[] g = {1, 2, 3, 4};
int[] h = Arrays.copyOf(g, g.length); // 배열과 함께 length값도 같이 넣어줌
// String 기능 예시
String str = "ABCD";
// (1) length
int strLength = str.length();
System.out.println(strLength);
// (2) charAt(int index)
char strChar = str.charAt(1);
System.out.println(strChar);
// (3) substring(int fromIDx, int toIdx)
String strSub = str.substring(0, 3);
System.out.println(strSub);
// (4) equals(String str)
String newStr = "ABCE";
boolean strEqual = newStr.equals(str);
System.out.println(strEqual);
// (5) toCharArray() : String -> char
char[] strCharArray = str.toCharArray();
// (6) 반대로 char[] -> String -> char
char[] charArray = {'A', 'B', 'C', 'D'};
String charArrayString = new String(charArray);
System.out.println(charArrayString);
💡 다차원 배열
배열의 논리적 메모리 구조가 2차원 이상의 형태를 보이는 배열
2차원 배열 선언 방법
int[][] array
int array[][]
int[] array[]
3차원 배열 선언 방법int[][][] multiArrary
1️⃣ ArrayList
ArrayList<Integer> intList = new ArrayList<>(); //선언 + 생성
// 값 추가
intList.add(1);
intList.add(2);
intList.add(3);
System.out.println(intList.get(0));
// 2번째 있는 값을 바꾸자
intList.set(1, 10);
System.out.println(intList.get(1));
// 삭제
intList.remove(0);
System.out.println(intList.get(0));
//전체 삭제
intList.clear();
System.out.println(intList.toString());
2️⃣ Linked List
// linked List
// 메모리에 남은 공간을 요청해서 나누어 값을 담음
// 실제 값이 있는 주소값을 목록으로 구성하고 저장
// 기본적 기능은 동일
// 조회 속도는 느리지만 추가/삭제는 빠름
LinkedList<Integer> linkedList = new LinkedList<>();
linkedList.add(1);
linkedList.add(3);
linkedList.add(30);
System.out.println(linkedList.get(0));
System.out.println(linkedList.get(1));
System.out.println(linkedList.get(2));
System.out.println(linkedList.toString());
linkedList.add(200);
System.out.println(linkedList.toString());
linkedList.add(1, 33);
System.out.println(linkedList.toString());
linkedList.set(0, 30);
System.out.println(linkedList.toString());
linkedList.remove(1);
System.out.println(linkedList.toString());
3️⃣ Stack
// Stack
// 수직으로 값을 쌓아놓고, 넣었다가 뺀다. FILO(Basket)
// push, peek, pop
// 최근 저장된 데이터를 나열하고 싶거나, 데이터의 중복 처리를 막고 싶을 때 사용
Stack<Integer> intStack = new Stack<Integer>();
// 추가
intStack.push(10);
intStack.push(23);
intStack.push(55);
// 다 지워질 때까지 출력
while (!intStack.isEmpty()) {
System.out.println(intStack.pop());
}
intStack.push(10);
intStack.push(15);
intStack.push(20);
// peek
System.out.println(intStack.peek());
System.out.println(intStack.size());
// Set(집합) : 순서 없고, 중복 없음
// 순서가 보장되지 않는 대신 중복을 허용하지 않음
// Set -> 그냥 쓸 수도 있음. 그러나 HashSet, TreeSet 등으로 응용 가능
// 생성자가 없는 껍데기라서 바로 생성 X
Set<Integer> intSet = new HashSet<>();
intSet.add(1);
intSet.add(12);
intSet.add(20);
intSet.add(1);
intSet.add(9);
for (Integer value: intSet) {
System.out.println(value);
}
System.out.println(intSet.contains(2));
System.out.println(intSet.contains(5));
// Queue : FIFO
// add, peek, poll
// 생성자가 없는 인터페이스
Queue<Integer> intQueue = new LinkedList<>();
intQueue.add(1);
intQueue.add(5);
intQueue.add(9);
while (!intQueue.isEmpty()) {
System.out.println(intQueue.poll());
}
intQueue.add(1);
intQueue.add(5);
intQueue.add(9);
System.out.println(intQueue.peek());
System.out.println(intQueue.size());
// Map : key - value pair
// key라는 값으로 unipue하게 보장이 되어야
// Map -> HashMap, TreeMap으로 응용
Map<String, Integer> intMap = new HashMap<>();
intMap.put("one", 1);
intMap.put("two", 2);
intMap.put("three", 3);
intMap.put("three", 4);
intMap.put("three", 5);
// key 값 전체 출력
for (String key: intMap.keySet()) {
System.out.println(key);
}
// value 값 전체 출력
for (Integer value: intMap.values()) {
System.out.println(value);
}
System.out.println(intMap.get("three"));
- 입력값
- 저장할 자료구조명을 입력합니다. (List / Set / Map)
- 내가 좋아하는 요리 제목을 먼저 입력합니다.
- 이어서 내가 좋아하는 요리 레시피를 한문장씩 입력합니다.
- 입력을 마쳤으면 마지막에 “끝” 문자를 입력합니다.
- 출력값
- 입력이 종료되면 저장한 자료구조 이름과 요리 제목을 괄호로 감싸서 먼저 출력 해줍니다.
- 이어서, 입력한 모든 문장앞에 번호를 붙여서 입력 순서에 맞게 모두 출력 해줍니다.
package week02.collection;
import java.util.*;
public class Recipe {
public static void main(String[] args) {
// 자료구조 요리 레시피 메모장 만들기
//
// - 입력값
// - 저장할 자료구조명을 입력합니다. (List / Set / Map)
// - 내가 좋아하는 요리 제목을 먼저 입력합니다.
// - 이어서 내가 좋아하는 요리 레시피를 한문장씩 입력합니다.
// - 입력을 마쳤으면 마지막에 “끝” 문자를 입력합니다.
// - 출력값
// - 입력이 종료되면 저장한 자료구조 이름과 요리 제목을 괄호로 감싸서 먼저 출력 해줍니다.
// - 이어서, 입력한 모든 문장앞에 번호를 붙여서 입력 순서에 맞게 모두 출력 해줍니다.
Scanner sc = new Scanner(System.in);
// 자료구조명 입력받기
System.out.println("저장할 자료구조명을 입력하세요 (List/Set/Map)");
System.out.print(" > ");
String coll = sc.nextLine();
// List 일 때
if (Objects.equals(coll, "List")) {
// List 선언, 생성
LinkedList<String> recipe = new LinkedList<>();
제목 입력받기
System.out.println("제목을 입력하세요");
System.out.print(" > ");
String title = sc.nextLine();
// 내용 입력받기
System.out.println("내용을 한 문장씩 입력하세요");
while (true) {
System.out.print(" > ");
String input = sc.nextLine();
// input이 끝이면 중단, 끝이라는 단어는 저장하지 않음
if (Objects.equals(input, "끝")) {
break;
}
recipe.add(input);
}
System.out.println("[ List로 저장된 " + title + " ]");
// 저장된 만큼 출력
for (int i = 0; i < recipe.size(); i++) {
System.out.println((i + 1) + ". " + recipe.get(i));
}
// Set 일 때
} else if (Objects.equals(coll, "Set")) {
// 순서를 주기 위해서 LinkedHashSet 사용
LinkedHashSet<String> recipe = new LinkedHashSet<>();
// 제목 입력받기
System.out.println("제목을 입력하세요");
System.out.print(" > ");
String title = sc.nextLine();
// 내용 입력받기
System.out.println("내용을 한 문장씩 입력하세요");
while (true) {
System.out.print(" > ");
String input = sc.nextLine();
// input이 끝이면 중단, 끝이라는 단어는 저장하지 않음
if (Objects.equals(input, "끝")) {
break;
}
recipe.add(input);
}
System.out.println("[ Set으로 저장된 " + title + " ]");
// LinkedSet은 Iterator를 통해 값을 꺼내와야 한다.
Iterator iter = recipe.iterator();
// 저장된 만큼 출력
for (int i = 0; i < recipe.size(); i++) {
System.out.println((i + 1) + ". " + iter.next());
}
// Map 일 때
} else if (Objects.equals(coll, "Map")) {
// Map 선언, 생성
Map<Integer, String> strMap = new HashMap<>();
// 제목 입력받기
System.out.println("제목을 입력하세요");
System.out.print(" > ");
String title = sc.nextLine();
// key에 해당하는 숫자
int inputNum = 0;
// 내용 입력받기
System.out.println("내용을 한 문장씩 입력하세요");
while (true) {
System.out.print(" > ");
String input = sc.nextLine();
// input이 끝이면 중단, 끝이라는 단어는 저장하지 않음
if (Objects.equals(input, "끝")) {
break;
}
// key-value 형태로 저장
strMap.put(inputNum++, input);
}
System.out.println("[ Map 으로 저장된 " + title + " ]");
// 저장된 만큼 출력
for (int i = 0; i < strMap.size(); i++) {
System.out.println((i + 1) + ". " + strMap.get(i));
}
// List/Set/Map이 아닌 다른 값을 입력받았을 때
} else {
System.out.println("잘못된 값이 입력되었습니다.");
}
}
}
뭐랄까 생각보다 어렵지 않았기 때문에 뚝딱뚝딱 만들었다.
<결과값...!>