switch와 if문의 가장 큰차이는 조건의 차이 이다.

switch

switch (n){
    case 1:
        ~
        break;

    case 2:
        ~
        break;
    case 3:
        ~
        break;
        ...

if

 if(조건 ){

 }
 else if(){

 ]
 ..

언뜻 보기에 if가 편하다.

조건을 숫자뿐아니라 비교 연산등 마음대로 사용 가능하기 때문이다.

하지만 if는 위에서부터 조건을 하나 하나 순차적으로본다.

하지만 switch문은 들어오는 조건을 보고 즉각 조건에 해당하는 문장으로 진입한다.

switch는 또한 break를 사용하지않으면 뒤에 조건까지 줄줄이 읽게 되니 꼭 break를 걸어주도록 하자.

switch

정의

switch(조건)
{
case <조건1>:
    <조건이 참일때 시행할 것>
    break;
case <조건2>:
    <조건이 참일때 시행할 것>
    break;
case <조건3>:
    <조건이 참일때 시행할 것>
    break;
...
default :
<조건으로 원하는값을 넣어주지 않을때 시행할 것>

}

예제

if

정의

if(<조건>)
{
조건이 참일때 조건
}
else
{
조건이 참이아닐때 조건
}

예제

package day3;
import java.util.Scanner;
//문제: 더하기를 계속한다. 맞출때 어려운문제면 20점을 주고 쉬운문제면 10점을 준다.
//틀리면 총점수를 주고 끝낸다.
public class Test01 {
    public static void main(String[] args) {
        System.out.println("덧셈 계산 게임");
        int score=0;
        int count=0;
        while(count<5)
        {
            Scanner scan=new Scanner(System.in);
            int num1=(int)(Math.random()*100);
            int num2=(int)(Math.random()*100);
            System.out.printf("\n%d+%d=",num1,num2);
            int num3=num1+num2;
            int answer=scan.nextInt();
            if(answer==num3)
            {
                System.out.printf("\ntrue+30");
                score+=30;
                count++;
            }
            else
            {
                System.out.printf("\nwrong-10");
                score-=10;
                count++;
            }    
        }
        System.out.printf("\nyour score is %d",score);
        }
    }

for문

정석

for(int i=0;i<<조건>;i++)-->이러한 방식이다.

예제

        for(int i=0;i<5;i++)
        {
            Scanner scan=new Scanner(System.in);
            int num1=(int)(Math.random()*100);
            int num2=(int)(Math.random()*100);
            System.out.printf("\n%d+%d=",num1,num2);
            int num3=num1+num2;
            int answer=scan.nextInt();
            if(answer==num3)
            {
                System.out.printf("\ntrue+30");
                score+=30;
            }
            else
            {
                System.out.printf("\nwrong-10");
                score-=10;
            }    
        }
        System.out.printf("\nyour score is %d",score);
        }
    }

즉 for 과 while은 c 와 동일하다.

'언어 > java' 카테고리의 다른 글

class  (0) 2018.01.05
배열  (0) 2018.01.05
입력과 출력  (0) 2018.01.04
자료형  (0) 2018.01.04
자바-eclipse tutorial  (0) 2018.01.04

+ Recent posts