190519_Day10 복습, 미션풀이, not연산자, NullPointException, String

복습

  • 속성변수와 참조변수의 차이점

    • 속성변수

    • 데이터 값(value)를 담는 변수

    • 자료형 변수명;

    • 사용

      no = 300;
      System.out.println( no );
      System.out.println( no + 200 );
      System.out.println( no. ); //얘는 에러
    • 참조변수

    • 데이터 주소( addr )를 담는 변수

    • 자료형 변수명;

      • String Integer A NameMenu Person 등…
      A a; // a에 주소를 담겠음
      a = new A();
      
      System.out.println( a.su );
      System.out.println( a.hello() );
    • 정수 100 =>> 데이터 저장

    • 저장되는곳에 주목

    • 변수 : int su = 100; System.out.println( su );

    • 배열 : int su[] = { 100 }; int su[] = new int[3]; su[0] = 100;

    • 클래스

      class A
      {
        int su = 100;
      }
      A a = new A();
      
      출력은 System.out.println( a.su );
  • 속성변수와 참조변수 차이점 2

    • 값복사와 주소 복사
    int su1;
    int su2;
    
    su1 = 100;
    su2 = su1;
    //su1이 가지고 있는 데이터를 su2에 전달( 그릇 말고 내용만 )
    su1 = su1 * 200;
    // su1 : 20000 su2 : 100 아! 100이란 값은 두개가 있었구나, 주소가 다르구나
    A a1;
    A a2;
        a1 = new A(); 203호 메모리 가르킴
        a1.su = 100; //메모리 값 100으로 바뀜
        //a1.su 출력  : 100
        a2 = a1; // a2도 203호(가칭) 메모리를 가르킴

미션풀이

// 로또 중복 없이 6개 출력
import java.util.Random;

public class LottoTest 
{
    public static void main(String[] args) 
    {
        int lotto [ ] = new int [ 6 ];
        Random r = new Random();

        lotto[ 0 ] = r.nextInt( 6 ) + 1; // 0~44 까지라 1더하기!
        do 
        {
            lotto[ 1 ] = r.nextInt( 6 ) + 1; 
        }while(lotto[1]==lotto[0]);

        do
        {
            lotto[ 2 ] = r.nextInt( 6 ) + 1;
        }while( lotto[2] == lotto[1] ||
                lotto[2] == lotto[0]);

        do
        {
            lotto[ 3 ] = r.nextInt( 6 ) + 1;
        }while( lotto[3] == lotto[1] || 
                lotto[3] == lotto[0] || 
                lotto[3] == lotto[2]);

        do
        {
            lotto[ 4 ] = r.nextInt( 6 ) + 1;
        }while(lotto[4] == lotto[1] || 
                lotto[4] == lotto[0] || 
                lotto[4] == lotto[2] ||
                lotto[4] == lotto[3]);
        do
        {
            lotto[ 5 ] = r.nextInt( 6 ) + 1;
        }while( lotto[5] == lotto[1] || 
                lotto[5] == lotto[0] || 
                lotto[5] == lotto[2] ||
                lotto[5] == lotto[3] ||
                lotto[5] == lotto[4]);

        for( int i = 0; i < lotto.length; i++ )
        {
            System.out.println("lotto[" + i + "] = " + lotto[i]);
        }
    }
}
//로또
import java.util.Arrays;
import java.util.Random;

public class LottoTest2 
{
    int lotto[]; // null
    Random r; // null

    public LottoTest2() 
    {
        lotto = new int[6];
        r = new Random();
    }//생성자

    public void printNum() 
    {
        for (int i = 0; i < lotto.length; i++) 
        {
            System.out.print( lotto[ i ] + "\t");//6번
            if( i < 5 )System.out.print("\t");//5번
        }
    }

    public void generateNum()
    {
        for (int i = 0; i < lotto.length; i++ )
        {
            lotto[ i ] = r.nextInt(45) + 1; // 1에서 45까지 난수 발생!
            //세번째 데이터를 입력 i =>> 2

//          boolean flag = duplicateNum(i);
//          if(flag)
//          {
//              i--;
//          } 이를 줄여서 아래에
            if(duplicateNum(i))i--;

        }//for문
        Arrays.sort(lotto);
    } //generateNum

    //중복숫자 체크 기능, 중복 숫자 발견시 true 리턴~!
    public boolean duplicateNum(int idx)
    {
        for( int i = idx - 1; i >= 0; i--) //1~0 , 
        {
            if( lotto[idx] == lotto[i] )
            {
                return true;
            }
        }//for
        return false; // for문을 다 실행한 다음에 내려옴. if를 한번도 만족하지 않았다. 중복된 데이터를 찾기 못했다.
    }//duplicateNum

    public static void main(String[] args) //생성자 : 초기화 메소드, 선행작업
    {
        LottoTest2 lotto = new LottoTest2(); // 생성자 먼저 호출

        for(int i = 1; i<6; i++)
        {
            System.out.print(i + "회 : ");

            lotto.generateNum();
            lotto.printNum();
            System.out.println(" ");
        }

    }
}
//다른 로또 방법도 있다 45개 짜리 배열 만들고 랜덤으로 섞고 0번부터 5번까지 꺼내오기
import java.util.Arrays;
import java.util.Random;

public class LottoTest3 
{
    public static void main(String[] args) 
    {
        int[] lotto = new int [45]; // 인덱스 0~44
        Random r = new Random();

        //첫번째 방 ~ 마지막 방 숫자 입력 : 1~45
        for (int i = 0; i < lotto.length; i ++)
        {
            lotto[i] = i + 1;
        }

        //숫자를 섞어주기
        int temp;
        for(int i = 0; i<1000; i++) 
        {
            int randomIdx = r.nextInt(44) + 1; // 밑에서 랜덤이 두번 쓰이는데 같은곳을 지정하기 위해 미리 변수 선언
            temp = lotto[0];
            lotto[0] = lotto[randomIdx]; //0부터 44번지 + 1 중, 한개!
            lotto[randomIdx] = temp;        
        }


        for ( int i = 0; i < 6; i ++) // 배열 맨 앞의 6개 숫자를 출력
        {   Arrays.sort(lotto, 0, 6);
            System.out.println( "lotto[" + i + "] = " + lotto[ i ] );
        }
    }
}

package nameManuMission;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class NameMenuTest 
{
    public static void main(String[] args) throws IOException 
    {
        // 반복되는 메뉴출력( 화면 뷰 처리 )
        // 번호 입력을 위한 read() 또는 readLine() 메인에서 사용
        // 이름 입력을 위한 readLine() 메인에서 사용
        // 그러니까 통일성 위해 그냥 readline()쓰는게 좋겠넵...
        NameMenu menu = new NameMenu();
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String no;
        do
        {
            System.out.println("<이름메뉴>");
            System.out.println("1.추가  2.검색  3.수정  4.삭제  5.종료");
            System.out.print("번호를 입력해 주세요~ =>>");          
            no = in.readLine(); // no에는 "1" "2" "3" 과 같은 문자열이 들어온다~!

            switch(no)
            {
            case "1" : { // 밑에 또 case3 에name이 등장하기 때문에(다시 밑에도 이름 바꿈) 영역괄호로 묶어버린다~!
                        System.out.print("이름 입력 : ");
                        String name = in.readLine();
                        menu.add(name);
                        //메소드호출 : 메소드명(데이터)
                        System.out.println( name );
                        }
                        break;

            case "2" : 
                        menu.search();
                break;

            case "3" : 
                        System.out.print("변경하고자 하는 기존 이름 입력 : ");
                        String oldName = in.readLine();

                        System.out.print("새로 수정 하는 이름 입력 : ");
                        String newName = in.readLine();

                        menu.update(oldName, newName);
                break;

            case "4" : 
                        System.out.print("삭제 할 이름 입력 : ");
                        String delName = in.readLine();

                        menu.delete(delName);
            }//switch
        }
        while( !no.equals( "5" ) ); //번호에 1,2,3,4,5 입력했다면! , String클래스이기 때문에 == 으로 하면 값이 아닌 주소를 찾는다., equals로! 

        System.out.println("E N D");
        //논리데이터 앞에는 !(not) 연산자를 붙일 수 있다~!
        //<!not연산자>

    }//main
}
/===
package nameManuMission;

public class NameMenu 
{
    String names[]; // null

    public NameMenu()
    {
        names = new String[5];
    }

    //배열에 이름 저장
    public void add(String name)
    {
        //빈방찾기~!
        for( int i = 0 ; i < names.length; i++ )
        {
            if( names[i] == null ) //빈방을 찾았다면~!
            {
                names[i] = name;
                break;
            }
        }
    }

    //배열내의 이름들 조회
    public void search()
    {
        System.out.println("#이름목록");
        for( int i = 0; i<names.length; i++)
        {
            if(names[i] != null) 
                {
                System.out.println(names[i]);
                }
        }
    }

    //배열에 저장된 이름을 변경
    public void update(String oldName, String newName)
    {
        //oldName과 일치하는 이름을 배열에서 찾기
        for( int i = 0; i < names.length; i++) //배열 전체 인덱스
        {
//          if( names[i].equals( oldName ) )
//          {
                /*
                 * NullpointerException 방지
                 * 1. if(oldName.equals(names[i])) : oldName에 null값 절대 전달되지 않음
                 * 2. if(names[i] != null && names[i].equals(oldName))
                 *      : names[i]번지의 값이 null이 아닐 때 equals()메소드 호출!
                 */
                if(names[i] != null && names[i].equals(oldName))
                {
                names[i] = newName;
                break;
                }
        }


    }//update

    //배열에 저장된 이름을 삭제
    public void delete(String delName)
    {
        // 배열에 저장된 데이터 삭제표현 : 배열명[번지] = null;
        for( int i = 0; i < names.length; i++ )// 배열에서 삭제할 이름 찾기
        {
            if(names[i] != null)
            {
                if(names[i].equals(delName))
                {
                    names[i] = null;
                    break;
                }
            }

        }

    }//delete

}

NullPointerException 발생원인!

  • null이란 메모리 할당되지 않은 것을 의미한다.

  • 메모리 할당을 하지 않은 상태에서 필드 또는 메소드를 참조 했을 때 발생하는 에러!

  • null.필드명 null.메소드명(); 시 발생!

    class A
    {
      void hello()
      {
    
      }
    }
    
    class test
    {
      A a; //null
    
      void print()
      {
          a.hello(); //null.hello()한것과 같다, nullpoint에러
          a mew A(); // a에는 메모리 주소정보가 저장
          a.hello(); // 싫
      }
    
      public static void main(String []args)
      {
          Test t = new Test();
          t.print();
      }
    }
    aa.bb(dd); 
    =>> ㅁㅁ\\\\\\\\NullPointrExeption 을 발생 킬 수 있는 요소, 는? aa 90%, bb 1-%
    
    
    null.bb(dd); =>> 예외 발생
    aa.bb(null);  예회 발생하지 않음
    
    A aa;
    class A
    {
    
    }

String

package j0419;

public class StringTest 
{
    public static void main(String[] args) 
    {
//      String 자바 = "abc";
//      String str = 자바;

//      String 문자열 : 문자들의 나열!
        String str = "Java Programming";
        //인덱스 ```````012345678901234
        //총 문자 15개가 들어갔다. str은 참조변수, 클래스잖아~! 속성은 뒤에 . 안됨, 참조변수는 . 가능~!

        System.out.println(" 바꾼값 = " + str.replace("Java", "자바") );

        //str에서 부분 문자열 "Programming"을 구하시오.
        System.out.println(str.substring( str.indexOf('P') ));

        //str.substring(4);
        System.out.println("str.indexOf( \"am\" )" +str.indexOf( "am" ));

        //마지막 'a' 문자의 인덱스를 구하시오
        System.out.println("str.lastIndexOf( \'am\' )" +str.lastIndexOf( 'a' ));

        //문자열 치환(대체)
        System.out.println("str.replace('a', 'o') = " + str.replace('a', 'o'));

        //"JovoProgromming"이 str에 저장되길 원한다면
        str = str.replace('a', 'o');
        System.out.println("STR = " + str);


//      str.~ String클래스에 있는

        //문자열 길이( 문자 갯수 )
        System.out.println("str문자열길이( 문갯수 ) : " + str.length());

        //부분문자열 =>> "Pro" 문자열 얻기
        //substring( int beginIndex, int endIndex)
        System.out.println( "str.substring(4, 6) = " + str.substring( 4, 6 ) );//여기서 4,6은 파라미터
        //beginIndex : 시작인덱스( 포함 )
        //beginIndex :  끝 인덱스( 미포함 )
        //=>> str.substring( 4, 7 ) 은  인덱스4 ~ 인덱스6 까지

        //부분문자열 =>> "Programming" 문자열 얻기
        System.out.println(str.substring( 5, 8 ));
        System.out.println(str.substring( 5 )); // 시작인덱스부터 끝까지

        //특정인덱스의 문자 얻어오기 : char str.charAt(int index)
        System.out.println( "str.charAt(4) = " + str.charAt( 5 ) );

        //특정 문자의 인덱스 얻어오기
//      int str.indexOf(int ch);
        int index = str.indexOf(97); //97은 소문자 a
        int index2 = str.indexOf('a'); //97은 소문자 a
        System.out.println("index = " + index2);
        System.out.println("index = " + index);

        System.out.println( (char)97 );

        //replace(CharSequence target, CharSequence replacement)
        //CharSequence 부모 - String 자식
        str = "Java Programming";
        //문자열에 공백 추가~!
            str = " " + str + " "; //str 앞에 공백 2개 , 뒤에 공백 2개 추가 
            System.out.println( "공백 추가 후 STR = " + str );
            System.out.println( "STR문자열 길이 = " + str.length( ) );

            //문자열 제거! ( 문자열 앞 뒤 연속된 공백제거 ) 
            str = str.trim();
            System.out.println("공백 제거 후 STR = " + str );
            System.out.println( "STR문자열 길이 = " + str.length( ) );


    }
}
package j0419;

public class StringTest2 
{
    public static void main(String[] args) {

        String s1 = "java";
        String s2 = "JaVA";

        //문자열 s1, s2를 비교( 문자열 내용비교 ) 하시오. ★★★★★
        System.out.println("s1.equals(s2) = " + s1.contentEquals(s2)); // false : 대소문자 비교하기에~!
        //"java".equals( "JaVA" ) 사용가능

        //대소문자 구분없이 s1과 s2철자를 비교하시오
        System.out.println( "대문자변환" + s1.toUpperCase() );
        System.out.println( "소문자변환" + s2.toLowerCase() );

        System.out.println("전체 소문자(s1 s2) 변경 후 비교 = " + s1.toLowerCase().equals(s2.toLowerCase()));

        //문제) str문자열 안의 있는 숫자의 갯수를 화면에 출력하시오.
        //아스키 코드값  = 0은 48, a는 97 A는 65
        String str = "Java3Pro7gra9mm0ing"; // 화면에 '4' 출력


        int count = 0;
        System.out.println("str문자열길이( 문갯수 ) : " + str.length());
        for( int i = 0; i < str.length(); i++ )
        {
            char ch = str.charAt(i);
            if( ch > 47 && ch <60 ) //혹은 '0' '9'랑 비교해도 가능하다.
            {
                //숫자로 구성된 문자라면 
                count++;
                System.out.print(ch);
                if(i < str.length())
                System.out.print(", ");
            }
        }
        System.out.println("갯수 : " + count);

    }
}
궁금상자
    - 갑자기 든 생각인데 메모리 주소 출력 받은걸로 입력도 가능할까?

    - 하나의 for문안에 변수 2개

    - 로또 하 면서 봤는데 
    for( int i = dex - 1; i > -1; i--)는 되고 for( int i = dex - 1; i == 0; i--)은 안되네?
        바보야 i == 0... 조건이 아니야...
    - 왜 0부터 5까지 배열을 Arrays.sort(lotto, 0, 6); 하면 되고 Arrays.sort(lotto, 0, 5); 하면 안되지?
        선생님이 알려주심 이상 미만의 범위라서 그럼..~!
    - String과 StringBuffer의 차이
        고정일땐 String 가변일 땐 StringBuffer???

+ Recent posts