언어/java

switch,if,while,for

leo_____lee 2018. 1. 4. 22:57

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 와 동일하다.