190417_Day8 라인단위 입력, 클래스 객체 생성, 배열, 2차원 배열
복습
추상클래스
메소드 구현을 상속받은 클래스에 강제한다.
자식클래스들을 제어할 목적
자식클래스들의 특징을 모아놓은 클래스
추상 클래스는 객체생성 new 불가 => 자식클래스 객체생성
형식
abstract class 클래스명 { int su; // 변수선언; 명시적 생성자; void hello() {} // 구현(정의)메소드; abstract void print(); // 선언 메소드, 이름만 짓고 , 자식클래스에서 기능넣기!, 얘는 접근제한자 안 적어도 public //*오버라이딩, 상속시에 자식 클래스는 반드시 부모클래스의 접근제한보다 같거다 커야 한다. }
클래스 사용 => 객체생성해서 사용
class A{ void hello(){} } //== A a = new A(); a.hello();
인터페이스 사용 => 클래스에 구현(implements)해서 사용
interface B {void hello(); } //== class a implements B { void hello(){} }
추상클래스 사용 => 자식클래스 객체 생성해서 사용
class Child extends Parent { void print() {} } //== A a = new A(); a.hello();
메소드 호출
public void my() { m1( ); // 1. 메소드 호출 m2(); // 에러 발생 m2( 500 ); // 3. 500을 넣어서 매개변수 통해 전달,데이터 혹은 데이터를 담은 변수안의 데이터를 줘야 한다. int num = m3( ); //6. 반환 받은 값 800을 num을 선언하며 초기화 } //== void m1( ) // 이름을 불러주세요 { 문장1; 문장2; 문장3; } // 2. 반환 void m2( int su ) // 정수 데이터 주세요 { }// 4. 반환 int m3( ) // 결과값을 정수로 드릴게요 { return 800; //5. 반환 }
//이거 좀 많이 헷갈리네...
class Parent{ }
class Child extends Parent{ }
//-------
//<메소드 정의>
pulic void hello( Child c )
{
}
public void goodBye( Parent p )
{
//Parent p = new Child(); 대체 가능
}
//-------
//<메소드 호출>
hello(new Child());
//위와 같은 표현
Child cc = new Child();
hello( cc );
hello(new Parent( ) ); //? 안됩니다. 자식객체에 부모객체가 들어갈 수 없다!
//--------
goodBye(new Parent); // 가능
Parent pp = new Parent();
goodBye( pp );
goodBye( new Child( ) ); //가능!
//--------
void a(String greeting)
{
}
String b(int su)
{
return "안녕하세요";
}
int c()
{
return 500;
}
//--------
a( b( c( ) ) ); //이런식으로도 가능하다! c-> b-> a 순으로 실행됨
//<--실행순서---
//--------
<라인단위입력>
클래스 BufferedReader –>> 메소드 readLine()
API문서 정보 =>> BufferedReader
A a = new A();
Reader r = new Reader(); =>>(x)=>> 추상클래스 : 자식 ==> InputStreamReaderInputStreamReader is = System.in;
Reader r = new InputStreamReader(); =>>(o)
BufferedReader br = new BufferedReader( r );
이렇게 3줄이 나와야 br.readLine(); 사용가능 줄을 구분자로 하는 text입력근데 is 나 r은 한번 쓰고 다시는 안쓰는데… 굳이 변수지정?!
BufferedReader br = new BufferedReader( new InpuStreamReader( System.in ) );클래스 객체 생성
멤버 필드, 멤버 메소드들에 대한 메모리 할당
동적 메모리 할당
사용안하는 객체에 대해서 가비지 컬렉터가 자동 소멸 관리
키워드 : new
사용법 : 참조변수를 통해 참조
A a = new A(); a.hello();
정적 메모리 할당
- 자주 사용되는 필드, 메소드에 대해 정의
- 객체들간의 통신에 사용 ( 공뷰 데이터를 표현 )
- 키워드 : static
- 사용법 : 클래스 명으로 참조
- 클래스명.필드명 클래스명.메소드명(); =>> 클래스변수, 클래스메소드
class B { static int su = 100; //static public == public static 이다! public static void goodBye(){} } //==================================== //<길동개발자> <라임개발자> //B.goodBye(); B.goodBye(); //Syso(B.su); 100출력 // B.su++; // Syso(B.su); 101출력!
//System.out.println(); //out은 필드 .println();은 메소드 public class System { static PrintStream out; }
//어제 mission 풀이
/*
*
**
***
****
*/
public class StarTest
{
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();
}
}
}
//========================== 거꾸로
public class StarTest
{
public static void main(String[] args)
{
for(int i = 4; i > 0; i--)
{
for(int j = 1; j <= i; j++)
System.out.print("*");
System.out.println();
}
}
}
배열
자료형이 동일한 데이터들에 같은(한개의) 변수명을 정의한 자료들의 집합.
자료형이 동인한 데이터들 => 조건
같은(한개의) 변수명을 정의=>특성
자료들의 집합 => 정의
int su; -> 한 개의 정수를 저장할 준비
int []su2; ->여러개의 정수를 저장할 준비
서로 데이터들을 구분하기 위해 번지를 사용.
시작번지는 0번지, 1씩 증가하는 번지를 가짐
배열의 크기가 정해지면 인덱스를 벗어나는 참조를 하면 안됨.
int [] su3 = { 10, 20, 30 };
번지 인덱스 = su3[0] su3[1] su3[2]
배열의 크기 ( 요소 갯수 ) : 3 ( 인덱스 0~2 )
<5000 데이터 출력>
System.out.println(5000); int su = 5000; System.out.println(su); int []suArr = { 5000 }; System.out.println( suArr[0] );
배열의 크기 ( 배열의 요소 갯수 ) 를 구하는 속성 : 배엷명.length (배열은 객체다)
배열선언시 []는 변수명 앞에 또는 뒤에 붙여도 상관이 없다.
int []su;
int su[];
.
int i;
int j;
int k;
===>> int i,j,k;
차이점)
int su1[],su2; =>> su1은 정수배열, su2는 정수
int [] su1, su2; =>> su1, su2 둘다 정수배열
참고)
class A { int i; // 기본값 존재 void hello() { int j; // 지역변수 기본값 존재 X System.out.println(i); // 출력? 0 System.out.println(j); // 출력? 초기화하지 않았다는 에러 발생 j = 0; System.out.println(j); // 출력? 0 int a,b,c = 0; System.out.println(b); // 출력? 에러 발생, c만 0으로 초기화 된거야!, 방지하려면 int a = 1, b = 2, c =0; 이렇게 각각 초기화까지 해줘야 한다! }//hello }
<배열형식>
자료형 [ ] 배열명 = { 데이터List( 콤마로 구분되는 데이터 ) };
=>> 배열 선언과 동시에 데이터를 초기화. ( 이미 데이터가 확정되었을 때 사용 )
=>> 주의 : 배열 선언과 데이터 초기화하는 부분을 따로 작성할 수 없음!
int [] su; // 배열선언 su = {1,2,3,4,5}; // 배열초기화 (X) //=== int [] su = { 1, 2, 3, 4, 5 } // 선언과 동시에 초기화 (o) //=== A a = new A(); a []su = { a, newA(), newA() };
자료형 [ ] 배열명 = new 자료형 [배열크기]; // 배열 객체 생성식 : 암기!
=>> 프로그램 실행 도중 데이터 값을 입력, 변경할 때 주로 사용
=>> 데이터가 정해지지 않고 앞으로 입력받을 데이터들이 저장될 방(공간)만 준비
==>> 배열선언과 데이터 초기화하는 부분을 따로 작성하는 것이 가능
==>> 배열 크기 []는 반드시 자료형 뒤에 위치해야 함
==>> 배열크기에 정수값이 반드시 입력되어야 함.
int []su; // 배열선언 su = new int[5]; //배열초기화 (su 배열변수에 5개의 정수를 입력 받겠음!) // 이는 이렇게 써 된다. int [] su = new int [5]; // 데이터 입력 su[0] = 11; su[1] = 22; su[2] = 33; su[3] = 44; su[4] = 55; su[5] = 66; // 얜 인덱스를 벗어났으므로 에러~! // 배열 객체생성( 위의 2번 ) 을 하게 되면 그 위치에 상관없이 각방에는 초기값이 부여됨 // ( 멤버변수 처럼 각 자료형의 기본값이 입력됨 )
public class ArrayTest
{
public static void main(String[] args)
{
//1. 배열 선언과 초기화
// int []su;
// su = { 1, 2, 3, 4, 5 }; 에러 발생 : 반드시 선언과 동시에 초기화를 함게 기술할 것!
int []su = { 1, 2, 3, 4, 5 }; // 이렇게 선언과 동시에 초기화 할 것! { su[0], su[1], su[2], su[3], su[4] }
int su1[] = { 1, 2, 3, 4, 5 };
System.out.println( "su[0]번지 = " + su[0]);
System.out.println( "su[1]번지 = " + su[1]);
System.out.println( "su[2]번지 = " + su[2]);
System.out.println( "su[3]번지 = " + su[3]);
System.out.println( "su[4]번지 = " + su[4]);
// System.out.println( "su[5]번지 = " + su[5]); 에러발생 인덱스를 벗어남!
System.out.println("=====================================");
System.out.println("배열의 크기 ( 요소갯수 ) " + su.length);
for(int i = 0; i < su.length; i++ )
{
//배열의 인덱스 표현 ( 0, 4)
System.out.println("su[ "+ i + " ]번지 = " + su[i]);
}
}
}
package Rand;
import java.util.Random;
public class RandArrayTest
{
int []su; // null 값이 들어감
Random r;
public RandArrayTest()
{
su = new int[5]; // [0]번지 ~ [4]번지 생성
r = new Random();
}
public void inputArray()
{
for (int i = 0; i < su.length; i++)
{
//랜덤(임의의 난수) 수를 발생해서 배열안에 입력
//su[i] = (int)( Math.random() * 100 ); //0.0 ~ 0.999999999... * 100 을 다섯번 호출, 캐스팅이 우선순위라 괄호 하기
// ----- 캐스팅 연산자 (형변환 연산자)
su[i] = r.nextInt(1000) + 1; // 0~999, + 1 : 0~1000
}
}
public void printArray()
{
for(int i = 0; i < su.length; i++)
{
System.out.println("su[ " + i + " ] = " + su[i] );
}
}
public void sortArray() {}
public static void main(String[] args)
{
RandArrayTest rat = new RandArrayTest();
rat.inputArray();
rat.printArray(); // 배열값 출력
}
}
/*
su[ 0 ] = 804
su[ 1 ] = 782
su[ 2 ] = 632
su[ 3 ] = 57
su[ 4 ] = 375
*/
//swap
package Rand;
public class SwapTest
{
public static void main(String[] args)
{
int su1 = 50;
int su2 = 30;
int temp = su1; //임시변수 temp = 50;
//교환식
su1 = su2; // su1 = 30;
su2 = temp; // su2 = 50;
System.out.println( "su 1 = " + su1 ); //30
System.out.println( "su 2 = " + su2 ); //50
//---------------------
int []arr = { 300, 100 };
//배열의 값 변경
temp = arr[0];
arr[0] = arr[1];
arr[1] = temp;
System.out.println( "arr[0] = " + arr[0] );
System.out.println( "arr[1] = " + arr[1] );
}
}
package Rand;
import java.util.Random;
public class RandArrayTest
{
int []su; // null 값이 들어감
Random r;
public RandArrayTest()
{
su = new int[5]; // [0]번지 ~ [4]번지 생성
r = new Random();
}
public void inputArray()
{
for (int i = 0; i < su.length; i++)
{
//랜덤(임의의 난수) 수를 발생해서 배열안에 입력
//su[i] = (int)( Math.random() * 100 ); //0.0 ~ 0.999999999... * 100 을 다섯번 호출, 캐스팅이 우선순위라 괄호 하기
// ----- 캐스팅 연산자 (형변환 연산자)
su[i] = r.nextInt(1000) + 1; // 0~999, + 1 : 0~1000
}
}
public void printArray()
{
for(int i = 0; i < su.length; i++)
{
System.out.println("su[ " + i + " ] = " + su[i] );
}
}
public void sortArray()
{
int temp;
for(int i = 0; i < 4; i++) // 비교할 왼쪽(기준) 데이터 0 1 2 3 4
{
for(int j = i + 1; j < 5; j++) // 비교 오른쪽 데이터 1, 2, 3, 4 2,3,4 3,4 4
{
if(su[i] > su[j]) //정렬조건 오름차순 ex) 정렬 12345, abcde, 가나다라마
{
//i와 j는 배열의 번지수를 표현
temp = su[i];
su[i] = su[j];
su[j] = temp;
}
}
}
}
public static void main(String[] args)
{
RandArrayTest rat = new RandArrayTest();
rat.inputArray(); //난수 데이터를 배열에 입력
rat.sortArray(); //데이터 정렬(오름차순)
rat.printArray(); // 배열값 출력
}
}
<2차원배열>
실제 저장은 1차원 배열과 같으나 논리적으로 데이터를 행과 열의 형태로 저장한다고 생각, 표현.
행 사이즈는 반드시 기술해야 하며, 열 사이즈는 생략하는것이 가능
//배열선언 int [][]su; int su[][]; int []su[]; //대괄호의 위치는 상관이 없다. // ----0행---- ----1행---- int [][]su = { { 1, 2, 3 }, { 4, 5, 6 } }; // ------- -------- // 열:0,1,2 열:0,1,2 System.out.println(su[0][2]); //0행 2열 데이터 =>> 3 System.out.println(su[1][1]); //1행 1열 데이터 =>> 5 su.length // 행의 갯수 => 2 su[0].length //== 0행의 열의 갯수 =>> 3 su[1].length //== 1행의 열의 갯수 =>> 3 for( int i = 0; i < su.length; i++ ) //기준(행) : 행의 인덱스 표현 { for( int j = 0; j < su[i].length; j++ ) //각 행의 열 인덱스 : 0, 1, 2 { System.out.prinln( su[i][j] ); // su i행 j열 } }
public static void main(String[] args) { RandArrayTest rat = new RandArrayTest(); rat.inputArray(); //난수 데이터를 배열에 입력 rat.sortArray(); //데이터 정렬(오름차순) rat.printArray(); // 배열값 출력 int [][]su2 = { { 1, 2, 3 }, { 4, 5, 6 } }; System.out.println( "su2배열의 행 갯수" + su2.length ); System.out.println( "su2배열 첫번째 행의 열(데이터) 갯수 " + su2[0].length ); System.out.println( "su2배열 두번째 행의 열(데이터) 갯수 " + su2[1].length ); //전체 데이터 조회 for(int i = 0; i < su2.length; i++) { for(int j = 0; j < su2[i].length; j++ ) { System.out.println("su2[" + i + "][" + j + "] = " + su2[i][j]); } } } /* su2배열의 행 갯수2 su2배열 첫번째 행의 열(데이터) 갯수 3 su2배열 두번째 행의 열(데이터) 갯수 3 su2[0][0] = 1 su2[0][1] = 2 su2[0][2] = 3 su2[1][0] = 4 su2[1][1] = 5 su2[1][2] = 6 */
//mission package mission; public class Mission0417 { public static void main(String[] args) { int su[] = { 1, 2, 3, 4, 5}; System.out.println("================<1번>==============="); for( int i = 0; i < su.length; i++ ) { System.out.print(su[i] + "\t"); } System.out.println(); System.out.println("================<2번>==============="); for( int i = su.length - 1 ; i >= 0; i-- ) { System.out.print(su[i] + "\t"); } System.out.println(); System.out.println("================<3번>==============="); int su2[][] = { { 1 }, { 1, 2 }, { 1, 2, 3 } }; for( int i = 0; i < su2.length; i++) { for( int j = 0; j <= su2[i].length - 1; j++) { System.out.println("su[ " + i + " ] [ " + j + " ] = " + su2[i][j]); } } System.out.println(); System.out.println("================<4번>==============="); int su3[] = {5, 5, 5, 5, 5}; for ( int i = 0; i < su.length; i ++) { su3[i] = su[i]; } System.out.println(su[2]); System.out.println(); System.out.println("================<5번>==============="); int temp; temp = su[0]; su[0] = su[4]; su[4] = temp; temp = su[1]; su[1] = su[3]; su[3] = temp; temp = su[0]; for (int i = 0; i < su.length; i++) { System.out.print(su[i] + "\t"); } System.out.println(); System.out.println("================<6번>==============="); temp = su[0]; su[0] = su[4]; su[4] = temp; temp = su[1]; su[1] = su[3]; su[3] = temp; temp = su[0]; for (int i = 1; i < su.length; i+=2) { System.out.print(i+ "번지" + "\t"); } System.out.println(); System.out.println("================<7번>==============="); temp = su[0]; for (int i = 0; i < su.length; i+=2) { System.out.print(su[i] + "\t"); } } } /* ================<1번>=============== 1 2 3 4 5 ================<2번>=============== 5 4 3 2 1 ================<3번>=============== su[ 0 ] [ 0 ] = 1 su[ 1 ] [ 0 ] = 1 su[ 1 ] [ 1 ] = 2 su[ 2 ] [ 0 ] = 1 su[ 2 ] [ 1 ] = 2 su[ 2 ] [ 2 ] = 3 ================<4번>=============== 3 ================<5번>=============== 5 4 3 2 1 ================<6번>=============== 1번지 3번지 ================<7번>=============== 1 3 5 */
궁금상자
- 동적, 정적 메모리가 변화 있고 없고 차이가 아니었나보네? 알아보자!
-
'클라우드 기반 웹 개발자 과정 공부 > JAVA' 카테고리의 다른 글
190519_Day10 복습, 미션풀이, not연산자, NullPointException, String (0) | 2019.04.19 |
---|---|
190118_Day9 복습, 삼항연산자, 클래스 객체 비교, 오토박싱 언박싱 (0) | 2019.04.18 |
190415 Day7 this, interface, mission, 배열, 자바빈즈, 추상클래스- (0) | 2019.04.16 |
190415 Day6 이클립스 설치, 접근지정(제한)자, 자기참조연산자, 인터페이스, final, 클래스와 인터페이스 간의 상속 문법 (0) | 2019.04.15 |
190412 Day5 Escape Character, printf, OOP, 오버라이딩, 오버로딩, 생성자 (0) | 2019.04.12 |