1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 | package com.test; import java.util.Scanner; public class String { //Ctrl + space -> Code Assist(코드자동완성기능) //Ctrl + d -> 행단위 삭제 //Ctrl + alt -> 행단위 위치 바꾸기 //Ctrl + / -> 단일라인 주석 //Ctrl + shift + / -> 다중라인 주석 public static void main(String[] args) { //문자열, String //주석 : Ctrl + / //다중 : Ctrl + Shift + / //m1(); //m2(); //m3(); //m4(); //m5(); //m6(); //m7(); //m8(); m9(); } private static void m9() { //9. 포함 유무 String str = "안녕하세요~ 홍길동님~"; System.out.println(str.contains("홍길동")); //'홍길동'이란 글자가 이 안에 있나? System.out.println(str.indexOf("홍길동") > -1); } private static void m8() { //8. 치환 함수 // - 대상 문자열에서 특정 문자열을 찾아서 또 다른 문자열로 바꾸기 // - String replace(String old, String new) //ask] 특정인물에게 인사, 이름 수정 String str = "안녕하세요 홍길동님~"; //원본(은 건드리지 않는다!!) System.out.println(str.replace("홍길동", "아무게")); //홍길동에서 -> 아무게로 변환 //추가1] str = "안녕히가세요 홍길동님~"; System.out.println(str); //old value 1개 이상일떄 -> 일괄 치환 System.out.println(str.replace("홍길동", "아무게")); //ask]주민번호를 입력("-"입력하면x) -> 쓰던지 말던지 상관없게., ****유용한 삭제 기능! String jumin = "851031-1454784"; System.out.println(jumin.replace("-", "")); //삭제(모든 하이픈) //추가]모든공백제거하기 String str2 = " 하나 둘 "; System.out.println(str2.replace(" ", "")); //모든 공백을 제거 //이름 수정하는 것, replace없이 바꾸는 다른 방법 str = "안녕하세요~ 홍길동님~"; String oldStr = "홍길동"; String newStr = "아무게"; //replace없이 //1. odlStr(홍길동)을 찾는다 int index = str.indexOf(oldStr); //'홍길동'의 위치? -> 7 String temp1 = str.substring(0, 7); //'안녕하세요~' 잘라내기 String temp2 = str.substing(index + oldStr.length()); //'님~' 잘라내기 System.out.println(temp1 + newStr + temp2); //temp1,2 합치기 //추가] 주민번호 앞자기(6), 뒷자리(7)을 분리 String jumin = "851021-1454784" //ask] 쇼핑몰이 있다 // - 옵션1. 빨강, 2.파랑, 3.노랑 Stirng color ="2"; String colorText = ""; //선택한 색상 if (color.eqauls("1")) colorText = "빨강"; else if (color.equals("2")) colorText = "파랑"; else if (color.equals("3")) colorText = "노랑"; System.out.printf("선택한 색상은 %색 입니다.\n, colorText"); //추가] 위에거 replace로 표현하기.. (열거형 데이터에 쓰기 좋다) color = "3"; colorText =color.replace("1", "빨강") .repalce("2", "파랑") .repalce("3", "노랑"); System.out.printf("선택한 색상은 %s색 입니다."); } private static void m7() { //7. 추출(일부) // - String substring(int startIndex), int endIndex -> 여기서부터 여기까지 잘라주세요 // - startIndex : inclusive // - endIndex : exclusive //ex)연습해보기 String str = "안녕하세요 홍길동님 반갑습니다."; System.out.println(str.substring(3, 8)); //출력] 세요 홍길 //ask] 주민번호에서 2,4번째 글자 찾기 String jumin = "901220-1024587"; //01234567 ..... 번째 System.out.println(jumin.substring(2,4)); //출력] 12 //ask] 문장에서 파일명만 찾아라 String path = "D:\\Java\\Hello.java"; int index = path.lastIndexOf("\\"); //뒤에서 부터 찾기..lastIndexOf를 사용 //path.substing(index+1, path.length() -1); String fileName = path.substring(index+1); //이걸로 쓴다 System.out.println(fileName); } private static void m6() { //6. 패턴 검색 // - boolean startsWith(String pattern) // - boolean endsWith(String pattern) //ex)연습해보기 String name = "홍길동"; //주어진 글자로 대상이 시작하는지 확인하는., //name이 "홍"으로 시작합니까? System.out.println(name.startsWith("홍")); //System.out.println(name.startswitch("010 //name이 "동"으로 끝납니까? System.out.println(name.endsWith("동")); //System.out.println(name.endswitch("4548")); //전화번호 뒷자리가 4548로 끝나는 사람? //유사형태., //시작 System.out.println(name.charAt(0) == '홍'); System.out.println(name.indexOf("홍") == 0); //끝 System.out.println(name.charAt(name.length() - 1) == '동'); System.out.println(name.lastIndexOf("동") == name.length() -1); } private static void m5() { //5. 대소문자 변환 **** // - String toUpperCase() //대문자 // - String toLowerCase() //소문자 //ex)연습해보기 String str = "Hello~ Hong~"; System.out.println(str.toUpperCase()); System.out.println(str.toLowerCase()); //언제 사용되나? -> 검색 //ex) java,Java,JaVa 뭐라고 검색하던 케이스를 통합해서 결과가 나온다 -> java, 소/대 하나로 ) //ex)연습해보기 String word = "hong"; //if (str.indexOf(word) > -1) { if (str.toUpperCase().indexOf(word.toLowerCase()) > -1) { //있다고 나오게 하려면 이걸써. System.out.println("발견"); } else { System.out.println("없음"); } } private static void m4() { //4. 검색 // - 문자열내에 원하는 문자(열)이 존재하는지 검색 // - 존재하면 해당 위치를 반환(index) // - int indexOf(char c) //기본 시그니쳐 // - int indeXOf(String s) //**** // - 못찾으면 -1을 반환* //ex)연습해보기 String str = "안녕하세요~ 홍길동님"; //호출 int index = str.indexOf("아무게"); //홍 찾아줘! System.out.println(index); //출력] 7 //어떤 경우에 사용되나? //ask] 어떤 게시판에 바보라는 단어가 쓰이면 안됨 str = "게시판에 글을 씁니다. 어쩌구 저쩌구 ~~"; //덮어쓰기 if (str.indexOf("바보") > -1) { System.out.println("금지어 사용 불가능!"); } else { System.out.println("글쓰기 완료~"); } //ask] 하이픈 사용유무 String jumin = "901220-2514512"; if (str.indexOf("-") == 6) { System.out.println("통과"); } //indexOf의 특징 // - 문자열의 처음부터 검색을 한다. // - 검색어를 발견하면 종료한다. (ctrl+f에서 단어찾을때 넘어가는 거 생각하면 됨) // - 오버로딩 돼 있따. //ask] '오'찾기 str = "일이삼사오육칠팔구십일이삼사오~"; System.out.println(str.indexOf("오")); //출력]4 System.out.println(str.indexOf("오", 0)); //기본값 System.out.println(str.indexOf("오", 5)); //출력] 14 //추가] '삼사오' 찾기 String word = "삼사오"; index = str.indexOf("삼사오"); System.out.println(index); System.out.println(str.indexOf("삼사오", index + word.length())); //int lastIndexOf(String s) // - indexOf와 유사 (indexOf의 친구) // - indexOf : 좌 -> 우 방향으로 검색 // - lastindexOf : 우 -> 좌 " //추가] 방향 비교해보기 System.out.println(str.indexOf("삼")); System.out.println(str.lastIndexOf("삼")); } private static void m3() { //3. 공백 제거 // - String trim() // - 문자열의 앞과 뒤의 공백을 모두 제거 // - 원본은 건드리지 않는다!!! *** String str = (" hong hong "); //원본 System.out.printf("[%s]\n", str); System.out.printf("[%s]\n", str.trim()); //출력] 트림처리, 앞뒤공백만 사라짐 (검색사이트에서 ' 자바 ' or '자바' 라고 검색해도 결과는 '자바'로 나온다. 사용자 편의성위해) System.out.printf("[%s]\n", str); str = str.trim(); //원본을 수정하고 싶으면 이렇게 써라.,(덮어쓰기)** } private static void m2() { //2. 추출 기능 // - 특정 위치의 문자를 추출하는 방법 // - char charAT(int index) // ->index에 위치한 문자 1개를 반환해주세요 // - 서수를 0부터 시작.. zero-based index이기 때문에 //ex)연습해보기 String str = "안녕하세요~"; //0 1 2 3 4 5번째 //ask] 3번째 문자를 가져오시오 char c = str.charAt(3); //3번째 문자를 반환 System.out.println(c); //ask] 마지막 문자를 가져오시오. c = str.charAt(str.length() - 1); //length -1해줘야 주문한 값이 나온다 System.out.println(c); //ask] 모든 글자를 탐색해보기 for (int i=0; i<str.length(); i++){ System.out.printf("str.chartAt(%d) = '%c'\n" ,i ,str.charAt(i)); //ask] 주민번호 입력 ("-" 반드시 입력) String jumin = "901201-2014789"; if (jumin.charAt(6) == '-') { System.out.println("올바른 주민번호"); } else { System.out.println("올바르지 않은 주민번호"); } //ask] 위에 주민 번호는 남성? 여성? if (jumin.charAt(7) == '1') { System.out.println("남자"); } else if (jumin.charAt(7) == '2') { System.out.println("여자"); } //추가]12라는 숫자 뽑아내기 char m1 = jumin.charAt(2); char m2 = jumin.charAt(3); System.out.println(m1); System.out.println(m2); System.out.println("" + m1 + m2); //추가]뭐였지? System.out.println((int)m1 - 48); System.out.println((int)m2 - 48); int n1 = (int)m1 - 48; //'1'-> 1 int n2 = (int)m2 - 48; //'2'-> 1 System.out.println(n1 + n2); System.out.println((n1 *10) + n2); //유효성 검사하기 //ask] 영소문자 단어 입력 후 맞는지 틀린지? String word = "te5st"; //올바른 문장이라는 전제하에 boolean result = true; for (int i=0; i<word.length(); i++) { char c2 = word.charAt(i); //if (c2 >= 'a' && c2 <= 'z') //유효성 검사를 할때에는 원하지 않는것 검사하는게 좋기때문에 if (c2 < '가' || c2 > '힣') { //이렇게 쓰는게 작업하기 좋다. System.out.println("소문자만 가능합니다!!!"); result = false; break; } } if (result) System.out.println("성공~"); else System.out.println("실패~"); } private static void m1() { //참조형 //Scanner scan = new Scanner(System.in); //String s2 = new String("홍길동님 안녕하세요"); //String의 기본시그니처 String s1 = "홍길동님 안녕하세요. hello~"; //1. 문자열의 길이 // - 몇글자? // - int length() //문자열할때 기본적으로 쓰이는 구문 System.out.println(s1.length()); //출력] 18자 (글자하나당 1개로 취급한다) //ask] 이름 입력받아 글자수가 몇 개, 통과/거절? Scanner scan = new Scanner(System.in); System.out.print("이름 : "); String name = scan.nextLine(); int length = name.length(); //유효성 검사 // - 2자 ~ 5자이내 if (length >= 2 && length <= 5) { System.out.println("통과~"); } else { System.out.println("거절~"); } } } | cs |
WEB/JAVA
- STRING1 2015.05.22
- FOR문2 2015.05.22
- FOR문1 2015.05.22
- SWITCH문 2015.05.22
- IF문 2015.05.22
- 날짜&시간2 2015.05.22 4
- 날짜&시간1 2015.05.22
- 메소드6 (예제) 2015.05.22
- 메소드5 (재귀 메소드) 2015.05.22
- 메소드4 (메소드 오버로딩) 2015.05.22
STRING1
2015. 5. 22. 00:22
FOR문2
2015. 5. 22. 00:18
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 | import java.util.Scanner; class for { public static void main(String[] args) { //m1(); m2(); //m3(); //m4(); //m5(); //do while문은 신경안써도 됨 //m6(); } public static void m6() { //ask] 회원관리 프로그램 콘솔 구현하기*** // 1. 회원 등록 // 2. 회원 보기 // 3. 회원 삭제 // 4. 종료 Scanner scan = new Scanner(System.in); boolean loop = true; //불형 루프사용 while (loop) { System.out.println("=============="); System.out.println("==회원 관리==="); System.out.println("==1.회원등록=="); System.out.println("==2.회원보기=="); System.out.println("==3.회원삭제=="); System.out.println("==4.회원등록=="); System.out.println("=============="); System.out.print("선택 : "); String sel = scan.nextLine(); //선택한 업무 실행 if (sel.equals("1")) { add(); } else if (sel.equals("2")) view(); else if (sel.equals("3")) del(); else loop = false; }//while System.out.println("프로그램 종료"); } public static void add() //메인에서 작업하면 너무 커져서 메소드로 빼주는게 좋다 { System.out.println("회원등록"); } public static void view() { System.out.println("회원보기"); } public static void del() { System.out.println("회원삭제"); } public static void m5() { //do while문 : 선실행 후조건(조건과 무관하게 무조건 1회 실행-> 조건에 따라서 계속 반복 유무 결정됨) /* do { 실행문; } while (조건식); */ int n = 1; do { System.out.println(n); n++; }while(n < 11); } public static void m4() { //while문 : 선조건 후실행 /* while (조건식) { 실행문; } */ //ask] 숫자 1~10 출력하기 (if문과 같은 쓰임) int n = 1; //초기식 while (n < 11) //조건식 { System.out.println(n); n++;//증감식 } } public static void m3() { for (int i=0; i<10; i++) { for (int j=0; j<10; j++) { if (i == 5) //j가5이면 브레이크 하라, 숫자 대입해가며 연습해보기 break; //직접 포함된 제어문만 탈출한다(j for문) System.out.printf("i : %d, j : %d\n", i, j); // 실행횟수는? } } } public static void m2() { //2중for문 구구단.. for (int j=2; j<10; j++) //2부터 9단까지.. { for (int i=1; i<10; i++) { System.out.printf("2 x %d = %2d\n", j, i, j*i); } System.out.println(); //단순 행바꾸기 } } public static void m1() { //제어문 중첩 //2중 for문 for (int i=0; i<10; i++) { for (int j=0; j<10; j++) { //System.out.println("안녕~"); //실행횟수는? System.out.printf("i : %d, j : %d\n", i, j); //출력] i크게회전 j작게회전 hour와 minute느낌 /* //3중 for문 for (int k=0; k<10; j++) { //1000회 회전 for (int l=-; l<10; l++) { //10000회 } } */ } } } } | cs |
FOR문1
2015. 5. 22. 00:16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 | import java.util.Scanner; import java.util.Calendar; class for { public static void main(String[] args) { //반복문 // - 공통점 : /* for (초기식;조건식;증감식) //3개의 문장이 들어있는 { 실행문; //반복코드 } */ //m1(); //m2(); //m3(); //m4(); //m5(); //m6(); m7(); } public static void m7() { //break, continue //break : 자신이 포함된 제어문을 탈출(if문 제외) // -m6의 응용3과 유사역할 //continue : 반복문의 처음으로 돌아가라~, 루프의 일부만 제외하고 건너뛸 때 사용. for (int i=1; i<11; i++) { if (i == 5) //i가 5면 브레이크 { //break; //for문 탈출 //출력 : 1,2,3,4 continue; //출력 : 1~10중 5가 빠져있음., } System.out.println(i); } //ask]선생님-> 학생상담하는데 ->break) 10번부터는 내일하자.. 스톱! // continue) 결석한 10번, 15번은 건너뛰자.. for(int i=1; i<31; i++) { if (i == 10) { break; } if (i == 10 || i == 15) { continue; } System.out.printf("%d번 학생 상담중..\n", i); } } public static void m6() { //무한루프 /* for (int i=0; 1<10; i--) { System.out.println("안녕~"); } */ /*응용]1 for (;;) { System.out.println("하하하~"); } */ /* //응용]2 //for (int i=0; true; i++) //true는 빼고 써도 된다. for (int i=0; ; i++) { System.out.println(i); } */ //응용]3. 특정상황에서 튀어나가는 루프 boolean loop = true; for (int i=0; loop; i++) { System.out.println(i); Calendar c = Calendar.getInstance(); if (c.get(Calendar.SECOND) == i) //초 가져오기, 0~59중에 하나가 반환 { loop = false; //루프탈출 } } } public static void m5() { //ask] 사용자가 입력한 10개의 숫자의 합을 구하시오 Scanner scan = new Scanner(System.in); int sum = 0 ; //2. 누적변수 만들기 for (int i=0; i<10; i++) //1. { System.out.print("숫자 : "); int n = scan.nextInt(); sum += n; } System.out.print(sum); } public static void m4() { //ask] 누적값 구하기 //1~10까지의 합 //1~100 //27~87 // 1 + 2 + 3 + 4 ... + 9 +10 int sum = 0; //누적 변수 (0으로 초기화) //for (int i=1; i<11; i++) for (int i=2; i<101; i+=2) //출력] 홀수의 합 : 2550 { sum += i; } System.out.println(sum); } public static void m3() { //ask] 구구단 3단 출력하기 //-> 패턴을 파악해야 한다. // 3 x 1 =3 // 3 x 2 =6 // 3 x 1 =9 // .. // 3 x 9 =27 for (int i=1; i<10; i++) //i<10 -> 9번 돌려야., i++ -> 증감치는 1씩., { System.out.printf("3 x %d = %2d\n", i, 3 * i); //%2 :오른쪽정렬 } } public static void m2() { //int i : 루프문(loop) -> 루프변수 //루프 변수의 역할 //1. 반복문의 실행 횟수 결정 //2. 루프 변수의 값을 사용 //요구사항] 숫자 1~10까지 출력 int n = 1; //1을 선언 for (int i=0; i<10; i++) { //System.out.println(n); //n = n + 1; //n에 대해 1씩 누적시키는 작업을 해줘야., //2. n = n += 1; //3. n++; System.out.println(i); } //응용]1. for (int i=1; i<11; i++) //i<11 -> 횟수가 10이면 만족하고 11이되면 빠져나가게 { System.out.println(i); } //응용]2. for (int i=1; i<11; i+=2) //i+=2 -> 2씩증가 -> 홀수출력 { System.out.println(i); } //응용]3. for (int i=10; i>0; i--) //i-- -> 1씩감소 { System.out.println(i); } } public static void m1() { //반복문Ex] //지역변수는 선언 위치에 민감하다, 충돌나지 않게 주의! int n; if (true) { n=10; System.out.println(n); } System.out.println(n); //int n; for (int i=0; i<10; i++) //?괄호가 어떻게 10번을 실행하게 만드는가? //초기값i=0, i가10보다 작을때까지, 1씩 증가한다 { System.out.println("안녕하세요~"); } //System.out.println(i); } } | cs |
SWITCH문
2015. 5. 22. 00:15
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 | class switch { public static void main(String[] args) { /* switch문, switch case문 switch (조건) { case 값: 실행문; break; case 값: 실행문; break; [case 값: 실행문; break;] x n회 [default: 실행문; break;] } */ //기본형] 숫자->문자 처리 int n = 2; switch (n) { case 1: System.out.println("하나"); break; case 2: System.out.println("둘"); break; //역할] 자신이 속한 제어문(switch)을 탈출 case 3: System.out.println("셋"); break; default: // 'int n = 값;'이 case 1~3범위에 안걸리는 경우 System.out.println("나머지 숫자"); } //ask]자판기 상황 만들어보기 java.util.Scanner scan = new java.util.Scanner(System.in); //1. 임포트 : 임포트 안하고 따오는 법(1회용) System.out.println("==============="); //2. 자판기 설정 System.out.println("=====자판기===="); System.out.println("==============="); System.out.println("===1. 콜라====="); System.out.println("===2. 사이다==="); System.out.println("===3. 비타500=="); System.out.println("==============="); System.out.println("선택 : "); //3.선택하기 String sel = scan.nextLine(); switch (sel) //4.조건작성하기 { case "1": System.out.println("700원 입니다."); //1의 값이 없으면 다음케이스의 조건과 공유한다 break; //break;의유무->case1의 break를 지워버리면(없으면) 다음 케이스로 실행시킨다.ㄴ case "2": System.out.println("700원 입니다."); break; case "3": System.out.println("500원 입니다."); break; } } } | cs |
IF문
2015. 5. 22. 00:14
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 | import java.util.Scanner; class if { public static void main(String[] args) { //제어문** // - 프로그램 코드의 실행 순서를 제어하는 역할 (8개) // - 실행순서를 잘본다. //1. 조건문 // a. if // b. switch //2. 반복문 // a. for // b. while // c. do while // d. for //3. 분기문 // a. break // b. continue // c. goto(x) //if문 //1 실행순서 // - 조건을 제시한 후 결과에 따라 실행할 문장을 선택 // - 조건문은 반드시 'boolean'값을 가져야 한다. **** /* if (조건문) //2 { 실행문; //3 } if (조건문) //2 { 실행문; //3 조건 만족 } //4 else { 실행문; //3 조건 불만족 } if (조건문) //2 { 실행문; //3 } //4 else if (조건문) //3 다른 조건은 어때? { 실행문; //4 } //5 else //기타 등등., { 실행문; 3 } */ //m1(); m2(); int n = 3; //실행문이 1줄일때는 {} 생략가능 if (n % 2 == 0) System.out.println("짝수"); else System.out.println("홀수"); //ask] 날짜 입력받아 요일 구하기 int day = 17; if (day % 7 == 0) System.out.println("일요일"); else if (day % 7 == 1) System.out.println("월요일"); else if (day % 7 == 2) System.out.println("요일"); else if (day % 7 == 3) System.out.println("수요일"); else if (day % 7 == 4) System.out.println("목요일"); else if (day % 7 == 5) System.out.println("금요일"); else if (day % 7 == 6) System.out.println("토요일"); //ask] 문자 소문자o/소문자x? char c = 'a'; // 문자 a int code = (int)c; // 문자 a를 형변환하여 코드값을 구한다 'a' -> 97 //if ( code >= 97 && code <= 122) //1. //if (code >= (int)'a' && code <= (int)'z') //2. if (c >= 'a' && c <= 'z') //3. 가독성 높음, 이 양식 사용 *** { System.out.println("소문자 0"); } else { System.out.println("소문자 x"); } //ask] 아이디 입력 //조건] 영문자 or 숫자 or _ 로만 구성할 수 있다. c = 'a'; if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_') //c가 소문자인지 대문자인지 숫자인지 { System.out.println("사용가능"); } else { System.out.println("사용 불가능"); } } public static void m2() { //ask] 국어 점수를 입력받아 "합격/불합격" 판단 int kor = 80; //1. //유효성 검사 코드 if (kor >= 0 && kor <= 100) { //비지니스 코드(업무코드) if (kor >= 60) { System.out.println("합격"); } else { System.out.println("불합격"); } } else //int kor = 값이 뜬금없이 나올 경우에 추가로, { //예외 처리 코드 System.out.println("점수는 0~100사이의 값을 입력하세요."); } //2. if (kor < 0 || kor > 100) { //예외 처리 코드 System.out.println("점수는 0~100사이의 값을 입력하세요."); } else { //비즈니스 코드(업무 코드) if (kor >= 60) { System.out.println("합격"); } else { System.out.println("불합격"); } } } public static void m1() { Scanner scan = new Scanner(System.in); //ask] 숫자 1개 입력 -> 조건] "양수" 판단 //입력 System.out.print("숫자 입력 : "); int num = scan.nextInt(); /* //조건: 기본골격 만들고 -> 조건만들어 넣기(만족했을때 조건먼저 작성) if (num > 0)//조건:특정num값이 0보다 크냐? { //조건 만족했을때 실행할 구문.. System.out.println("양수입니다."); } else { //조건 불만족., System.out.println("양수가 아닙니다."); } */ /* if (num > 0) { System.out.println("양수입니다."); } else if (num < 0) //양수가 아니면? { System.out.println("음수입니다."); } else if //(num == 0) { System.out.println("0입니다."); } */ //제어문 중첩 // - 제어문끼리는 중첩이 가능하다. //1. 숫자는 -10 ~ 10 사이로 입력 //선행조건 //2. 양수? 음수? 0인지? //2차조건, 선행조건 만족됐을시에만 실행하는., if (num >= -10 && num <= 10) //선행조건, 동등한 { if (num > 0) { System.out.println("양수"); } else if (num < 0) //2차 조건 { System.out.println("음수"); } } System.out.println("프로그램 종료"); } } | cs |
날짜&시간2
2015. 5. 22. 00:11
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 | import java.util.Calendar; import java.util.Date; class DateTime { public static void main(String[] args) { //m1(); m2(); } public static void m2() { //날짜 시간 연산 //현재 시간 Calendar now = Calendar.getInstance(); //-> 시간얻어오기 //ask] 오늘로부터 100일 뒤는? -> 200일 뒤는? // void add(int field, int value) //반환값 없고 이런 매개변수를 사용 now.add(Calendar.DATE, 100); System.out.printf("%tF\n", now); // 2015-03-27 //now.add(Calendar.DATE, 200); //System.out.printf("%tF\n", now); //주의! 이전값 03-27에 더해져서 300일이 출력됨 now.add(Calendar.DATE, 100); System.out.printf("%tF\n", now); //그래서 값을 100으로 //int n = 10; //n = 20; //ask] 지금으로부터 5시간 뒤는? now = Calendar.getInstance(); now.add(Calendar.HOUR, 5); //5시간뒤? System.out.printf("%tF %tT\n", now, now); //형식문자 2개이면, 뒤에 글자도 2개로 //ask]지금으로부터 100일전은? now = Calendar.getInstance(); now.add(Calendar.DATE, -100); System.out.printf("%tF\n", now); //ask] 지금으로부터 크리스마스가 몇시간 남았는지? // - 크리스마스 - 현재시간 = ? (빼기) now = Calendar.getInstance(); //현재시간 Calendar christmas = Calendar.getInstance(); //크리스마스 자정 christmas.set(2014, 11, 25, 0, 0, 0); //크리스마스가 되는 시점 //christmas - now; //크리스마스-현재시간 = ? //minus연산은 숫자만 돼서 에러가 뜸 -> 단위를 맞춰줘야 한다->틱값 구하기 //*tick값 구하기(1970.01.01 자정 기준 -> 1/1000초) //Date temp = now.getTime(); //long n = temp.getTime(); //System.out.println(n); // //*메소드 체이닝 long christmasTick = christmas.getTime().getTime(); //getTime() 2개는 서로 다른 객체이다. //->이 위치에 해당객체(Date)가 남음 long nowTick = now.getTime().getTime(); long gap = christmasTick - nowTick; //둘의 차이를 구하기 System.out.printf("올해 크리스마스는 총 %,d시간 남았습니다.\n", gap / 1000 / 60/ 60); //시 분 초로 나눠주기 } public static void m1() { //Calendar 객체 생성 //1. 현재 시간 얻어오기(지금) //2. 특정 시간 얻어오기(내생일) // - 현재시간 얻어온 후에 특정 시간 수정 //특정 항목 가져오기 // - int get(int field) //특정 항목 수정하기(넣기) // 1. void set(int field, int value) // 2. void set(int year, int month, int day, int hour, int minute, int second) // 하나하나 쓰기 힘드니까 이런st로 오버로딩하기 // 3. void set(int year, int month, int day) //현재시간 ask] 메소드 Calendar now = Calendar.getInstance(); //System.out.println(now); System.out.println(now.get(Calendar.YEAR)); // -> 1.읽기 //특정시간 ask] 1990년 5월 20일생 출력하기 Calendar birthday = Calendar.getInstance(); birthday.set(Calendar.YEAR, 1990); // -> 2.쓰기(넣기), 수정하기 birthday.set(Calendar.MONTH, 4); //5월생일 경우 -1, 0부터 시작 birthday.set(Calendar.DATE, 20); birthday.set(Calendar.HOUR_OF_DAY, 11); birthday.set(Calendar.MINUTE, 30); birthday.set(Calendar.SECOND, 0); birthday.set(1990, 4, 20, 11, 30, 0); // 간단st. 오버로딩 //System.out.println(burth.get(Calendar.YEAR)); System.out.println(birthday); //출력] //prindf() 메소드에 대응하는 형식문자 System.out.printf("%tF\n", birthday); //%tF //1990-02-20 System.out.printf("%tT\n", birthday); //11:30:00 System.out.printf("%tA\n", birthday); //일요일 System.out.printf("%tr\n", birthday); //11:30:30 오전 System.out.printf("%tR\n", birthday); //11:30 } } | cs |
날짜&시간1
2015. 5. 22. 00:11
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 | import java.util.Date; import java.util.Calendar; import java.util.Scanner; class DateTime { public static void main(String[] args) { //날짜 & 시간 //n:시간과 시각(특정한시점)은 자료형이 다르다, ex)2014.12.16시간 14h:15m:30s시각 //1. Date 클래스(구) //2. Calendar 클래스(신) -> 신버젼만 사용됨 //ex) 메소드 만들어 설명 //m1(); m2(); } public static void m1() { //Date 클래스 int n =10; Date d1 = new Date(); //**현재 시스템의 날짜 & 시간, 처음얻어온 시간이 저장돼있는 상태, 고정값 //(왼:변수) = (오:데이터) System.out.println(d1); Scanner scan = new Scanner(System.in); scan.nextLine(); System.out.println(d1); Date d2 = new Date(); //d2를 만들어 현재 시간의 데이터를 얻어온다 System.out.println(d2); } public static void m2() { //Calendar 클래스 //현재 시간 얻어오기 Calendar c1 = Calendar.getInstance(); //System.out.println(c1); ->c1의 덩어리 중에 뽑아와야.. //원하는 항목 가져오기 // int get(int n) int result = c1.get(1); System.out.println(result); result = c1.get(2); System.out.println(result); result = c1.get(3); System.out.println(result); //Calendar 상수제공 -> 변수 System.out.println(Calendar.YEAR); // result = c1.get(Calendar.YEAR); System.out.println(result); System.out.println(70); //이렇게만 써놓으면 70이 뭔지 모르잖아.. int weight = 70; //이렇게 System.out.println(weight); System.out.println(c1.get(Calendar.YEAR)); //년 System.out.println(c1.get(Calendar.MONTH)); //월(0~11) **0부터시작, 주의 System.out.println(c1.get(Calendar.DATE)); //일 System.out.println(c1.get(Calendar.HOUR)); //시(12) System.out.println(c1.get(Calendar.HOUR_OF_DAY)); //시(24) System.out.println(c1.get(Calendar.MINUTE)); //분 System.out.println(c1.get(Calendar.SECOND)); //초 System.out.println(c1.get(Calendar.MILLISECOND)); //밀리초 System.out.println(c1.get(Calendar.DAY_OF_WEEK)); //요일(일-1, 토-7) System.out.println(c1.get(Calendar.AM_PM)); //AM - 0, PM - 1 //오늘이 몇년 몇월 몇일입니까? System.out.printf("오늘은 %d년 %d월 %d일입니다.\n" , c1.get(Calendar.YEAR) , c1.get(Calendar.MONTH) + 1 //11월로 출력되므로 +1 해준다. , c1.get(Calendar.DATE)); } } | cs |
'WEB > JAVA' 카테고리의 다른 글
IF문 (0) | 2015.05.22 |
---|---|
날짜&시간2 (4) | 2015.05.22 |
메소드6 (예제) (0) | 2015.05.22 |
메소드5 (재귀 메소드) (0) | 2015.05.22 |
메소드4 (메소드 오버로딩) (0) | 2015.05.22 |
메소드6 (예제)
2015. 5. 22. 00:10
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | class Method { public static void main(String[] args) { //요구사항] 2개의 int값 -> 서로 교환하는 메소드 //요구사항] 2개의 String 값 > 서로 교환하는 메소드 int a = 10; int b = 20; //a에 20, b에 10을 넣어달라 String s1 = "홍길동"; String s2 = "아무게"; //swap() 메소드 // comm : 우유와 콜라컵, 빈컵(1개의 저장공간이 더 필요) // -정렬할 때 많이 사용 됨 swap(a, b); swap(s1, s2); } public static void swap(int a, int b) { System.out.printf("a : %d, b : %d\n", a, b); int temp;//빈컵 temp = a; a = b; b = temp; System.out.printf("a : %d, b : %d\n", a, b); } public static void swap(String a, String b) { System.out.printf("a : %s, b : %s\n", a, b); String temp; temp = a; a = b; b = temp; System.out.printf("a : %s, b : %s\n", a, b); } } | cs |
'WEB > JAVA' 카테고리의 다른 글
날짜&시간2 (4) | 2015.05.22 |
---|---|
날짜&시간1 (0) | 2015.05.22 |
메소드5 (재귀 메소드) (0) | 2015.05.22 |
메소드4 (메소드 오버로딩) (0) | 2015.05.22 |
메소드3 (지역변수) (0) | 2015.05.22 |
메소드5 (재귀 메소드)
2015. 5. 22. 00:08
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | class Method { public static void main(String[] args) { //재귀 메소드 Recursive Method // - 메소드가 자기 자신을 호출하는 메소드 //test(); //팩토리얼 //4! = 4 x 3 x 2 x 1 //4! = 24 int n = 4; int result = factorial(n); System.out.printf("%d = %d\n", n, result); } public static void test() { System.out.println("테스트"); test(); //***재귀호출 } public static int factorial(int n) { if (n == 1) { return 1; } else { return n * factorial(n -1); } } } | cs |
'WEB > JAVA' 카테고리의 다른 글
날짜&시간1 (0) | 2015.05.22 |
---|---|
메소드6 (예제) (0) | 2015.05.22 |
메소드4 (메소드 오버로딩) (0) | 2015.05.22 |
메소드3 (지역변수) (0) | 2015.05.22 |
메소드2 (구성요소) (0) | 2015.05.22 |
메소드4 (메소드 오버로딩)
2015. 5. 22. 00:06
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | class Method { public static void main(String[] args) { //메소드 오버로딩, Method Overloading // - 같은 이름의 메소드를 여러가 선언 // - 메소드 인자리스트를 다르게 구성하는 전제하에 // - 개발자를 위한., //요구사항] 두개의 데이터를 더하는 메소드 // 1. int + int // 2. double + double // 3. Stinrg + String // 4. 모든 기본자료형 대상으로 구현 sum(10, 20); //sum((int)1.5, (int)2.3); sum(1.5, 2.3); sum("홍길동", "아무게"); /* 메소드 오버로딩 조건 O 1. 인자의 갯수 2. 인자의 타입 메소드 오버로딩 조건 X 1. 인자의 이름 2. 반환값 타입 코드 작성중.. 호출 : test(); -> 1번이 대답 test(10); -> ? test("홍길동"); -> 4번 test(10, 20); -> 5번 int result = test(10); 1. public static void test() {} //o 2. public static void test(int n) {} //o 3. public static void test(int m) {} //x(2번과 충돌) 4. public static void test(String s) {} //o 5. public static void test(int n, int m) {} //o 6. public static int test(int n) {} //x(2번과 충돌, 호출 시 구분이 안감) */ } public static void sum(int a, int b) //자바는 이름을 'sum'이 아닌 'sum(int a, int b)'으로 //인식하기 때문에 넘버링 안해도 에러x //인자리스트가 달라졌으므로, { System.out.printf("%d + %d = %d\n", a, b, a + b); } public static void sum(double a, double b) { System.out.printf("%.1f + %.1f = %.1f\n", a, b, a + b); } public static void sum(String a, String b) { System.out.printf("%s + %s = %s\n", a, b, a + b); } } | cs |
'WEB > JAVA' 카테고리의 다른 글
메소드6 (예제) (0) | 2015.05.22 |
---|---|
메소드5 (재귀 메소드) (0) | 2015.05.22 |
메소드3 (지역변수) (0) | 2015.05.22 |
메소드2 (구성요소) (0) | 2015.05.22 |
메소드1 (0) | 2015.05.22 |