[ while문 ]


 형식)

 

while(조건식){

      반복실행할 문장;

  ...

 }

 ==> 조건이 거짓이 될때까지 반복해서 문장을 수행함

 


 

ex> while문 사용해서 1부터100까지 합 구하기

class MyTest02_while{

    public static void main(String[] args) {

        int sum=0,i=1;

        while(i<=100){

            sum+=i;

            i++;

        }

        System.out.println("1부터100까지 합:"+sum);

    }

}

 



[ 다중 while문 ]

 

 - 형식

 

while(조건식){

     while(조건식){

         반복실행할 문장;

           ...

    }

}

 

 

ex> 값을 입력받아 ( 2~9 사이값) 구구단을 출력한다.

import java.utill.Scanner;


class  MyTest03{

    public static void main(String[] args)  {

        Scanner scan=new Scanner(System.in);

        int i=1;

        while(true){

            System.out.println("단입력(종료:0)");

            int dan=scan.nextInt();

            if(dan==0) break;

            if(dan>9 || dan<2){

                System.out.println("2에서 9사이의 수 입력");

                continue;//초기의 조건식으로 분기

            }

            i=1;

            while(i<=9){

                System.out.println(dan+"*"+i+"="+dan*i);

                i++;

            }

        }

    }

}


 

 

 

 


 

[ do~while ]


- 형식

 

do{

      반복실행할 문장;

  ..

 }while(조건식);

 

==> 조건이 거짓일때까지 반복적으로 수행한다.



ex> 1 ~100까지 합구하기 / 2~9 사이 값 입력 받아 구구단 출력하기 를 do while사용하기

import java.util.Scanner;

class MyTest04_doWhile{

     public static void main(String[] args){

 

          //예1 do~while사용해서 1부터 100까지 합구하기

          int sum=0,i=1;

 

          do{

               sum+=i;

               i++;

          }while(i<=100);

 

          System.out.println("1부터100까지합:"+sum);

 

          //예2 단입력받아 구구단 출력

          Scanner scan=new Scanner(System.in);

 

          int dan=0;

 

          do{

               System.out.println("단입력(2에서9사이 수 입력)");

               dan=scan.nextInt();

           }while(!(dan>=2 && dan<=9));

 

          System.out.println("["+dan+"단]");

 

          for(int j=1;j<=9;j++){

               System.out.println(dan + "*"+ j + "=" + dan*j);

          }

     }

}

 



ex> 난수를 발생시키는 객체 생성하기

import java.util.Random;

 

class MyTest05_Random{

      public static void main(String[] args)  {


          //난수를 발생시키는 객체 생성하기

          Random rnd=new Random();

          for(int i=1;i<=5;i++){

               int n=rnd.nextInt(10);//0부터 9까지의 난수 발생하기

               System.out.println("발생된 난수:" + n);

          }

     }

}

 

 

 

'JAVA' 카테고리의 다른 글

클래스( class )  (0) 2014.09.12
배열( array )  (0) 2014.09.12
반복제어문( for문 )  (0) 2014.09.12
switch문  (0) 2014.09.12
IF문  (0) 2014.09.12

 

[반복제어문]


1. for문



형식1)


 for(초기식;조건식;증감식){

    반복 수행할 문장;

 }

--> 조건이 만족하지 않을때까지 반복적으로 문장을 수행한다.

 

 


 형식2)


for(초기식;조건식;증감식){

     for(초기식;조건식;증감식){

       반복 수행할 문장;

      }

 }

 


ex>

class MyTest12_for

{

    public static void main(String[] args) 

    {

        int i;

        //for사용해서 1부터 100까지 출력하기

        for(i=1;i<=100;i++){

            System.out.print(i+" ");

        }

        //홀수출력

        System.out.println();

        for(i=1;i<=100;i+=2){

            System.out.print(i+" ");

        }

        System.out.println();

        //1부터 100까지 합 구하기

        int sum=0;

        for(i=1;i<=100;i++){

            //sum=sum+i;

            sum+=i; 

        }

        System.out.println("1부터 100까지합:"+sum);

        //1부터100까지 수중 짝수합,홀수합을 구해보세요.

        int sum1=0;

        for(i=1;i<=100;i+=2){

            //sum=sum+i;

            sum1+=i; 

        }

        System.out.println("1부터 100까지 홀수합:"+sum1);

        int sum2=0;

        for(i=0;i<=100;i+=2){

            //sum=sum+i;

            sum2+=i; 

        }

        System.out.println("1부터 100까지 짝수합:"+sum2);

        sum1=0;sum2=0;

        for(i=1;i<=100;i++){

            if(i%2==1){

                sum1+=i;

            }else{

                sum2+=i;

            }

        }

        System.out.println("홀수합:" + sum1 +",짝수합:"+sum2);

    }

}

 

 

ex>  1부터 50까지 수중 3의 배수를 출력하고 3의 배수합도 출력하세요.


 3 6 9 .... 48

 3의 배수합:xxx

 

class MyTest13_for

{

    public static void main(String[] args) {

        int sum=0;

        for(int i=3;i<=50;i+=3){

            //3의 배수 출력

            System.out.print(i+" ");

            sum+=i;//3의 배수합 구하기

        }

        System.out.println("\n3의 배수합:"+sum);

    }

}

 

 


형식2)


for(초기식;조건식;증감식){

    for(초기식;조건식;증감식){

        반복 수행할 문장;

    }

}


ex>

class MyTest01_for{

    public static void main(String[] args){

        for(int i=1;i<=5;i++){

            for(int j=1;j<=i;j++){

                System.out.print("*");

            }

            System.out.println();

        }

    }

}

 



 

'JAVA' 카테고리의 다른 글

배열( array )  (0) 2014.09.12
반복제어문( while문 )  (0) 2014.09.12
switch문  (0) 2014.09.12
IF문  (0) 2014.09.12
관계/논리/대입/쉬프트 연산자  (0) 2014.09.12


[ switch ]


- 일치되는 값을 찾아 선택적으로 문장 수행


- 형식

switch(변수 또는 수식){

    case 비교값1:수행할 문장;break;

    case 비교값2:수행할 문장;break;

    case 비교값3:수행할 문장;break;

    ...

    default: 일치되는 값이 없을때 수행할 문장;

   }


주의> case 절에 비교되는 값은 정수형상수 또는  String 만이 올수 있다.(조건절 X,실수 X)

    (double 으로 테스트 해보면 이와같은 에러가 난다. : 

   Cannot switch on a value of type double. Only convertible int values, strings or  enum variables are permitted )


 

ex>

import java.util.Scanner;

class MyTest11_switch

{

    public static void main(String[] args) 

    {

        Scanner scan=new Scanner(System.in);

        System.out.println("상품번호입력");

        int n=scan.nextInt();

        switch(n){

            case 1:System.out.println("축하합니다! 상품 : TV");

            case 2:System.out.println("축하합니다! 상품 : 컴퓨터");

            case 3:System.out.println("축하합니다! 상품 : 스마트폰");break;

            case 4:System.out.println("축하합니다! 상품 : 카메라");break;

            default:System.out.println("상품이 없습니다.");

        }

        char ch='A';

        switch(ch){

            case 'A':System.out.println("축하합니다! 상품 : TV1");break;

            case 'B':System.out.println("축하합니다! 상품 : 컴퓨터1");break;

            case 'C':System.out.println("축하합니다! 상품 : 스마트폰1");break;

            case 'D':System.out.println("축하합니다! 상품 : 카메라1");break;

            default:System.out.println("상품이 없습니다.");

        }

    }

}

 


case 를 여러개 가져갈 경우는 


...

case 1:

case 2:

case 3:

      System.out.println(...);

case 4:

      System.out.println(...);


...


이와 같이 사용하면 된다.




 

 

'JAVA' 카테고리의 다른 글

반복제어문( while문 )  (0) 2014.09.12
반복제어문( for문 )  (0) 2014.09.12
IF문  (0) 2014.09.12
관계/논리/대입/쉬프트 연산자  (0) 2014.09.12
연산자  (0) 2014.09.12

 

[ 제어문 ]

 

1. 조건제어문

 - 조건에 따라 문장을 실행하거나 건너뜀

 

 형식1)

 if(조건절){

    조건이 참일때 수행할 문장;

 }

 

 형식2)

 if(조건절){

     조건이 참일때 수행할 문장;

 }else{

     조건이 거짓일때 수행할 문장;

 }



ex>

import java.util.Scanner;


class  MyTest07_if

{

    public static void main(String[] args)  {

        Scanner scan=new Scanner(System.in);

        int a,b;

        System.out.println("첫번째 수 입력");

        a=scan.nextInt();

 

        System.out.println("두번째 수 입력");

        b=scan.nextInt();

        int max=0;

        if(a>b){//a=10,b=20

            max=a;

        }else{

            max=b;

        }

        System.out.println(a+"와"+b +" 중에서 큰 수는" + max+"입니다.");

    }

}




[ if~else if문 ]

- 조건이 여러개인 경우 사용

- 형식

   if(조건1){

        수행할 문장;

   }else if(조건2){

        수행할 문장;

   }else if(조건3){

        수행할 문장;

   }

   ...

   else{

      조건이 모두 거짓일때 수행할 문장;

   }


ex>

class  MyTest08_if

{

    public static void main(String[] args)  

    {

        int a=-10;

        if(a>0){

            System.out.println(a+"는 양수입니다.");

        }else if(a<0){

            System.out.println(a+"는 음수입니다.");

        }else{

            System.out.println(a+"는 영입니다.");

        }

    }

}

 

ex>

class MyTest09_if

{

    public static void main(String[] args)

    {

        char ch='1';

        if(ch>='A' && ch<='Z'){

            System.out.println(ch+"는 대문자입니다.");

        }else if(ch>=97 && ch<=122){

            System.out.println(ch+"는 소문자입니다.");

        }else{

            System.out.println(ch+"는 알파벳이 아닙니다.");

        }

    }

}

 

ex>

import java.util.Scanner;

class MyTest10_if

{

    public static void main(String[] args) 

    {

        Scanner scan=new Scanner(System.in);

        System.out.println("아이디 입력");

        String id=scan.next();

        System.out.println("비밀번호 입력");

        String pwd=scan.next();

        //문자열을 비교할때는 ==가 아니라 equals를 사용한다.

        if(id.equals("song") && pwd.equals("1234")){

            System.out.println(id +"님 반갑습니다.");

        }else{

            System.out.println("아이디 또는 비밀번호가 틀려요.");

        }

    }

}

 

 

 

'JAVA' 카테고리의 다른 글

반복제어문( for문 )  (0) 2014.09.12
switch문  (0) 2014.09.12
관계/논리/대입/쉬프트 연산자  (0) 2014.09.12
연산자  (0) 2014.09.12
변수, 자료형  (0) 2014.09.12

 

[ 관계연산자 ]


- 두값의 대소를 비교

 >, >=, ==(같다), <, <=, !=(같지않다.)

 

EX> 관계연산자

MyTest01.java

class MyTest01

{

    public static void main(String[] args) 

    {

        int a=10,b=20;

        boolean b1=a==b;

        boolean b2=a!=b;

        System.out.println("b1:"+b1);

        System.out.println("b2:"+b2);

    }

}

 

 



[ 논리연산자 ]

 

!(not) : 어떠한값이 참이면 거짓,거짓이면 참으로 바꿈

 

&& (and) : 대응되는 값이 모두 참이면 참,아니면 거짓

 

|| (or) : 대응되는 값이 모두 거짓이면 거짓,아니면 참

 

ex>

MyTest02.java

import java.util.Scanner;


class MyTest02

{

    public static void main(String[] args)  

    {

        Scanner scan=new Scanner(System.in);

        System.out.println("면접점수");

        int interview=scan.nextInt();

        System.out.println("영어점수");

 

        int eng=scan.nextInt();

 

        if(interview>=80 || eng>=90){

            System.out.println("당신은 합격입니다.");

        }else{

            System.out.println("당신은 불합격입니다.");

        }

    }

}


 




 [ 대입연산자 ] 

 

 

 연산자

 의미 

 a+=b

a = a + b 

 a-=b

a = a - b 

 a*=b

a = a * b 

 a/=b

a = a / b 


  

ex>

class MyTest03

{

    public static void main(String[] args)  

    {

        int a=3,b=4,c=5,d=6;

        a+=10;     //a=a+10;

        b-=5;      //b=b-5;

        c*=2;      //c=c*2;

        d/=3;      //d=d/3;

        System.out.println("a:"+a);    //a:13

        System.out.println("b:"+b);    //b:-1

        System.out.println("c:"+c);    //c:10

        System.out.println("d:"+d);    //d:2

    }

}


--------------------------------------

a:13

b:-1

c:10

d:2

 

 


ex>

class MyTest04

{

    public static void main(String[] args)  

    {

        int a=2;

        int b=5;

        int c=a|b;         //대응되는 비트값이 하나라도 참(1)이면 참

        int d=a&b;        //대응되는 비트값이 모두 참이면 참

        int e=a^b;        //대응되는 비트값이 서로 다르면 참

 

        System.out.println("c:"+c);

        System.out.println("d:"+d);

        System.out.println("e:"+e);

    }

}


-----------------------------


c:7

d:0

e:7


 




 [ 쉬프트 연산자 ]


 정수<<n : 정수를 좌측방향으로 n비트 이동

 정수>>n : 정수를 우측방향으로 n비트 이동



ex>

class MyTest05

{

    public static void main(String[] args) {

        int a=7;

        int b=a<<2;

        int c=a>>2;

        System.out.println("b:"+b);

        System.out.println("c:"+c);

    }

}





instanceof : ~타입의 객체인지 판별

                                                    

참조변수  instance of 클래스명       


ex>

class MyTest06

{

    public static void main(String[] args)  

    {

        String str="안녕";

        ////str이 String타입의 객체냐?

        if(str instanceof String)

        {

            System.out.println(str +"은 String 타입의 객체입니다.");

        }

        if(str instanceof Object){

            System.out.println(str +"은 Object 타입의 객체입니다.");

        }

    }

}




'JAVA' 카테고리의 다른 글

switch문  (0) 2014.09.12
IF문  (0) 2014.09.12
연산자  (0) 2014.09.12
변수, 자료형  (0) 2014.09.12
JDK다운로드, 설치, 이클립스 다운  (0) 2013.01.24

+ Recent posts