제어문
1. 조건문
삼항연산자는 속도가 더 빠르지만 메모리를 더 많이 잡아먹는다.
if문은 속도는 느리지만 메모리를 덜 잡아먹는다.
(3~4개의 조건식을 사용할 때에는 삼항연사자가 빠르지만 그 이상은 if문이 더 낫다.)
① if문
if(조건식){
실행할 문장
}
위에 있는 조건식과 상관없이 모두 검사.
if(조건식){
실행할 문장
}
if(조건식){
실행할 문장
}
if(조건식){
실행할 문장
}
위의 있는 조건식이 거짓이면 내려와서 검사, 참이면 검사 안함.
else if(조건식){
실행할 문장
}
else{
실행할 문장
}
Quiz (if문 사용해서 출력)
package day04;
import java.util.Scanner;
public class Quiz {
public static void main(String[] args) {
//삼항 연산자를 사용해서 정답이면 정답 출력, 오답이면 오답 출력
//Q. 다음 중 프로그래밍 언어가 아닌 것은?
//1. JAVA
//2. 파이썬
//3. C언어ㅡ
//4. 망둥어
int choice = 0;
int answer = 4;
String resultMsg = "";
String msg = "Q. 다음 중 프로그래밍 언어가 아닌 것은?\n" + "1. JAVA\n" + "2. 파이썬\n" +
"3. C언어\n" + "4. 망둥어\n" + "정답은 ?";
Scanner sc = new Scanner(System.in);
System.out.println(msg);
choice = sc.nextInt();
if(choice == answer) {
System.out.println("정답!");
}else if(choice >0 && choice <5 ) {
System.out.println("오답..");
} else {
System.out.println("잘못입력하셨습니다. 다시 시도해주세요.");
}
System.out.println(resultMsg);
}
}
package day04;
import java.util.Scanner;
public class IfTest {
public static void main(String[] args) {
//정수 2개 입력
//Scanner
int num1 =0, num2 =0;
String n1Msg ="첫번째 정수 : ", n2Msg = "두번째 정수 : ";
String msg = "";
Scanner sc = new Scanner(System.in);
System.out.println(n1Msg);
num1 = sc.nextInt();
System.out.println(n2Msg);
num2 = sc.nextInt();
if(num1>num2) {
msg = "큰 값 : " + num1;
}else if(num1 != num2) {
msg = "큰 값 : " + num2;
} else {
msg = "두 수는 같습니다.";
}
System.out.printf("%s", msg);
}
}
package day04;
import java.util.Scanner;
public class IfTask {
public static void main(String[] args) {
//혈액형별 성격
String msg = "당신의 혈액형은?\n"+ "1. A\n2. B\n3. O\n4. AB" ;
String a_msg = "꼼꼼하고 마음에 잘 담아둔다.";
String b_msg = "추진력이 좋고 한다면 무조건 한다.";
String o_msg = "개성이 강해서 사교성이 좋다.";
String ab_msg = "착하다.";
String err_msg = "잘못입력하셨습니다.";
String result = "";
int choice = 0;
Scanner sc = new Scanner(System.in);
System.out.println(msg);
choice = sc.nextInt();
switch(choice) {
case 1:
result = a_msg;
break;
case 2:
result = b_msg;
break;
case 3:
result = o_msg;
break;
case 4:
result = ab_msg;
break;
default:
result = err_msg;
}
System.out.printf("%s", result);
}
}
② switch문
변수에 값x가 담겼을 때 이동만 되기 때문에
그 밑의 문장들을 모두 실행한다.
따라서 실행할 문장이 끝났다면
break(기타 연산자)를 사용해서 탈출한다.
switch(변수명){
case 값:
실행할 문장;
break;
case 값:
실행할 문장;
break;
case 값:
실행할 문장;
break;
...
default:
실행할 문장;
}
if문은 대소 비교 혹은 논리연산자를 사용할 때에 사용한다.
switch문은 하나의 변수에 담길 수 있는 여러 값을 비교할 때 사용한다.
2. 반복문
① for문
for(초기식; 조건식; 증감식){
실행할 문장;
}
조건식이 거짓이면 탈출
- 작동 순서
1. 초기식
2. 조건식
3. 증감식
4. 조건식
5. 증감식
...
package day04;
public class ForTest {
public static void main(String[] args) {
// for(int i = 0; i < 10; i= i+1) {
// System.out.println(i+1+ ". 손서연");
//
// }
// for(int i = 0; i < 10; i = i+1) {
// System.out.println(10 - i + ". 손서연");
//
// }
int result = 0;
//1~10까지의 합
for(int i = 0; i<10; i++) {
//result = result + i + 1;
result += i+1;
}
System.out.println("1~10까지의 합: " + result);
}
}
package day04;
import java.util.Scanner;
public class ForTask {
public static void main(String[] args) {
//100~1까지 출력
// for(int i =0; i < 100; i++) {
// System.out.println(100-i);
// }
//1~100까지 중 짝수만 출력
// for(int i =0; i<50; i++) {
// System.out.println((i+1)*2);
//
// }
//1~100까지의 합 출력
// int sum = 0;
//
// for(int i =0; i<100; i++) {
// sum += i+1;
// }
// System.out.println("1~100까지의 합: " + sum);
//1~n까지의 합 출력
// int result = 0;
// int sum = 0;
// Scanner sc = new Scanner(System.in);
//
// System.out.println("정수를 입력하세요.");
// result =sc.nextInt();
//
// for(int i =0; i<result; i++) {
// sum += i+1;
// }
// System.out.println("합 : " + sum);
//A~F까지 출력
// int result = 0;
// for(int i = 0; i<6; i++) {
// result = i+65;
// System.out.printf("%c", result);
// }
//A~F까지 중 C제외하고 출력
// for(int i =0; i<5; i++) {
// System.out.println((char)(i>1? i+66: i+65));
//
// }
// int temp = 0;
// for(int i = 0; i<5; i++) {
// temp =i;
// if(i>1) {
// temp++;
// }
// System.out.println((char)(temp+65));
// }
//aBcDeFgHiJkLmNoPqRsTuVwXyz 출력
// for(int i =0; i<26; i++) {
// if((i+1)%2 == 0) {
// System.out.printf("%c", i+65);
// }else {
// System.out.printf("%c", i+97);
//
// }
//
// }
for(int i = 0; i<26; i++) {
System.out.print((char)(i%2 ==0? i+97: i+65));
}
}
}
② while문 : 초기식과 증감식이 없다는 것은 변수가 없다는 것.
while(조건식){
실행할 문장;
}
for문은 반복횟수가 정해져 있을 때, 혹은 증감량이 필요할 때 사용한다.
whlie문은 반복횟수를 알 수 없을 때(몇번 반복할지 모를 때), 혹은 증감량이 필요 없을 때 사용한다.
package day04;
import java.util.Scanner;
public class WhileTest {
public static void main(String[] args) {
int choice = 0;
int answer = 4;
String resultMsg = "";
while (true) {
String msg = "Q. 다음 중 프로그래밍 언어가 아닌 것은?\n" + "1. JAVA\n" + "2. 파이썬\n" + "3. C언어\n" + "4. 망둥어\n" + "정답은 ?";
Scanner sc = new Scanner(System.in);
System.out.println(msg);
choice = sc.nextInt();
if (choice == answer) {
resultMsg = "정답!";
} else if (choice > 0 && choice < 5) {
resultMsg = "오답..";
} else {
resultMsg = "잘못입력하셨습니다. 다시 시도해주세요.";
}
System.out.println(resultMsg);
if (resultMsg.equals("정답!")) {
break;
}
}
}
}
③ do ~ while문
do{
실행할 문장;
}while(조건식);
package day04;
import java.util.Scanner;
public class Dowhile {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int choice = 0;
do {
System.out.println("1. 통신요금 조회\n2. 결제카드 변경\n" + "3. 분실 신고\n 0. 상담원 연결");
choice = sc.nextInt();
}while (choice != 0);
}
}
연산자
대입연산자(복합 대입 연산자, 누적 연산자)
+=, -+, *=, /=, %=, ... * %(모듈러스) : 나머지 연산자
① 대입연산자
int money = 10000;
//money = money - 1000
money -= 1000;
money는 9000이 된다.
② 누적연산자
int data = 10;
//data = data +1;
//data += 1;
data++;
③ 증감 연산자
전위형 : 해당 줄부터 바로 적용된다.
++data
--data
후위형 : 다음 줄부터 적용된다
data++
data--
package day04;
public class OperTest {
public static void main(String[] args) {
int data = 10;
// System.out.println(data++);
System.out.println(++data);
System.out.println(data);
}
}
④ 기타연산자
- break : 중괄호 영역 탈출(반복문), break 이후의 문장은 실행 x.
if문에서 break사용시 if문을 감싸고 있는 영역 탈출
- continue : 밑의 문장을 실행하지 않고 다음 반복으로 넘어가기(스킵)
package day04;
public class OperTest2 {
public static void main(String[] args) {
// 1~10까지 중 4까지만 출력하기(break)
// for (int i = 0; i < 10; i++) {
// System.out.println(i + 1);
// if (i == 3) {
// break;
// }
// }
// 1~10까지 중 4제외하고 출력하기(continue)
for (int i = 0; i < 10; i++) {
if (i == 3) {
continue;
}
System.out.println(i + 1);
}
}
}
필기
\
- 문자열은 '=='로 비교 불가.
_____ . equals( String A, String B )를 사용해야 한다. 문자열은 클래스이므로 메소드를 이용해야함.
- 개발을 할 때, 순서
기획안 -> 디자인 -> 개발
---------- 단축키 ----------
ctrl + shift + f : 자동 줄 맞춤
ctrl + shift + o :
-------------------------------
'JAVA' 카테고리의 다른 글
[WEB]DAY6_2차원 배열 (0) | 2020.02.17 |
---|---|
[WEB]DAY5_배열 (0) | 2020.02.17 |
[WEB]DAY3_입력 메소드(2), 연산자, 조건식 (0) | 2020.02.12 |
[WEB]DAY2_변수, 자료형, 주소, 서식문자, 형변환, 입력메소드(1) (0) | 2020.02.11 |
[WEB]DAY1_JAVA의 기본, 설치, 기본 구성 요소, 출력 메소드 (0) | 2020.02.10 |