동빈나_ 정리

728x90

[변수]

-데이터타입 출력

int intType = 100;

double doubleType = 150.5;

System.out.println(StringType);



System.out.println(intType);

System.out.println(doubleType);

System.out.println(StringType);



-final 키워드-> 상수 정의

public class Main {



final static double PI = 3.141592; //final 상수 선언



public static void main(String[] args) {



int r = 30;

System.out.println(r*r*PI);



}

-데이터 범위 넘어선 오버플로우의 개념 이해

public class Main {



final static int INT_MAX = 2147483647; //정수형 상수 최댓값



public static void main(String[] args) {



int a = INT_MAX;

System.out.println(a+1);

}
-사칙연산 프로그램 작성

int a = 1;

int b = 2;



System.out.println("a+b = " + (a+b));

System.out.println("a-b = " + (a-b));

System.out.println("a/b = " + (a/b));

System.out.println("a*b = " + (a*b));



}

[자료형] 데이터 타입

 

-double형을 이용하여 평균 구하는 프로그램 작성

double a = 10.3;

double b = 9.6;

double c = 10.1;



System.out.println((a+b+c)/3);



-아스키코드 기반의 char형 사용 -> a부터 z까지 출력 프로그램 작성

for (char i = 'a'; i<= 'z'; i++) {

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

}



-String의 substring함수 활용

String name = "Jong Doe";

System.out.println(name);

System.out.println(name.substring(0,1)); //substring 메소드 사용

System.out.println(name.substring(3,4));

 

[연산자]

-초를 입력받아 몇 분 몇 초인지 계산 프로그램



final static int SECOND = 1000;



public static void main(String[] args) {



int minute = SECOND / 60;

int second = SECOND % 60;



System.out.println(minute + "분"+ second+"초");



-++와 —연산의 개념 이해

int a = 10;

System.out.println("현재의 "+ a + "입니다.");

a++;

System.out.println("현재의"+ ++a + "입니다.");



System.out.println("현재의"+ a++ + "입니다.");



-삼항 연산자 이용 메소드 활용

public class Main {



public static void main(String[] args) {



int x = 50;

int y = 60;



System.out.println("최댓값은 "+ max(x, y) + "입니다.");

}

//반환형 함수이름 매개변수

static int max(int a, int b) { //더 큰 값 반환 메소드

int result = (a>b) ? a: b;

return result;

}



-pow() 이용한 거듭제곱 연산 프로그램 작성



double a = Math.pow(3.0, 20.0); //3의 20제곱

System.out.println("3의 20 제곱은"+ (int)a + "입니다.");

[조건문과 반복문]

-if문 이용 -> 문자열이 특정 문자열 포함 여부 프로그램 작성

String a = "I Love you";

if(a.contains("Love")) {

//포함하는 경우 실행부

System.out.println("Me too");

}

else {

//포함하지 않는 경우

System.out.println("I Hate you");

}



-문자열과 정수형 각각 조건문을 이용해 그 차이점

//문자열 비교 시 equals()메소드 활용

if(a.equals("Man")) {

System.out.println("남자입니다.");

}

-for문 이용 삼각형 출력 프로그램 작성

//이중 for문으로 삼각별 출력

for(int i =30; i > 0; i--) {



for (int j = i; j> 0; j--) {

System.out.print("*");

}

System.out.println();

}

-for문 이용 원 출력 프로그램 작성

final static int N = 15;

public static void main(String[] args) {



for (int i = -N; i<= N; i++) {

for (int j = -N; j <=N; j++) {

if(i*i + j*j <= N * N) {

System.out.print("*");

}

else {

System.out.print(" ");

}

}

System.out.println();

}





-break문 활용



int count = 0;

for(;;) {

System.out.println("츌력");

count++;

if(count == 10) {

break;

}

}

 

[기본 입출력]

-특정한 정수 입력받아 그대로 출력

Scanner scanner = new Scanner(System.in); //scanner 생성



System.out.print("정수 입력 : ");

int i = scanner.nextInt(); //정수 입력받아 저장

System.out.println("입력한 정수는 "+ i + "입니다."); //출력

scanner.close();



-파일에 차례로 입력된 모든 정수에 100 곱해 출력

File file = new File("input.txt"); //file 입출력

try {

Scanner sc = new Scanner(file);

while(sc.hasNextInt()) { //다음으로 읽어올 정수 존재하냐 ?

System.out.println(sc.nextInt() * 100 );

}

} catch (FileNotFoundException e) {

System.out.println("오류");

}

 

[객체지향 프로그래밍]

 

[사용자 정의함수]

-3개의 수 최대 공약수 찾기

int min;

if(a>b) {

if(b>c) {

min = c;

}

else {

min = b;

}

}else {

if(a>c) {

min = c;

}else {

min = a;

}

}

//가장 작은 값이 min에 저장된 상태

for(int i = min; i>0; i--) {

if(a%i == 0 && b % i == 0 && c % i ==0) {

return i;

}

}

return -1; //최대공약수 없는 경우 -1반환

}



public static void main(String[] args) {



System.out.println("400, 300, 740 의 최대 공약수" + function(400,300,750)+"입니다.")

}



-k번째 약수 찾기

public class Main {



public static int function(int number, int k) { //number의 k번째로 약수 찾기



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



if(number % i == 0) { //약수 찾고

k--; // 다음 약수 찾게 k-1 이동

if(k==0) { //k ==0 되면

return i; //k번째 약수 찾은 거니 반환

}

}

}

return -1; //비정상 종료

}



public static void main(String[] args) {



int result = function(3050, 10);

if(result == -1) {

System.out.println("10번째 약수는 없다" );

}

else {

System.out.println("10번째 약수는 "+ result+"입니다.");

}



}













-문자열에서 마지막 단어 반환하는 함수 작성

public class Main {



public static char function(String input) { // 매개값으로 들어온 문자열의

return input.charAt(input.length() -1 ); // 마지막 문자 반환

}



public static void main(String[] args) {



System.out.println("Hello World의 마지막 단어는 " + function("Hello World") + "입니다.");

}

}



-max() 이용 최댓값 저장 프로그램

public class Main {



public static int max(int a, int b) {

return (a>b) ? a: b;

}

public static int function(int a, int b, int c) {

int result = max(a,b); //a와 b 중 큰 값 반환

result = max(result, c); // 큰 값과 c 비교해서 더 큰 값 반환

return result; //최종 큰 값 반환

}



public static void main(String[] args) {



System.out.println("345, 567, 789 중 가장 큰 값"+ function(345,567,789));

}

 

[반복함수와 재귀함수]

-팩토리얼을 구현



//반복함수로 구현

public static int factorial(int number) { //팩토리얼 계산

int sum = 1;

for(int i = 2; i<= number; i++) {

sum *= i;

}

return sum;

}

//재귀함수로 구현 (함수 안에 다시 자기 함수 호출)

public static int reFactorial(int number) {

if(number == 1) {

return 1;

}else {

return number * reFactorial(number -1); // 5! = 5 * 4! 성질 이용

}

[배열]

: 데이터가 많을 때 동일한 데이터끼리 묶어서 관리

 

-원하는 개수만큼 배열 생성 및 최댓값 구하기

import java.util.Scanner;



public class Main {



public static int max(int a, int b) {

return (a>b)? a: b;

}



public static void main(String[] args) {



Scanner scanner = new Scanner(System.in);

System.out.print("생성할 배열 크기 입력: ");

int number = scanner.nextInt();

int[] array = new int[number];



for(int i = 0; i< number; i++) { //입력받은 값으로 배열 채우기

System.out.print("배열 내부값 차례로 하나씩 입력: ");

array[i] = scanner.nextInt();

}



int result = -1;

for(int i = 0; i< number ; i++) { //내부 배열 돌면서

result = max(result, array[i]); // 무조건 더 큰 값이 최종 저장됨

}

System.out.println("입력한 배열 값 중에서 가장 큰 값은 " + result) ;



}

}

-100개의 랜덤 정수 평균 구하는 프로그램

public class Main {



public static void main(String[] args) {



int[] array = new int[100]; //넉넉하게 배열 생성

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

array[i] = (int) ( Math.random() *100 + 1);

}



int sum = 0;

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

sum += array[i] ;

}

System.out.println("평균값은"+ sum/100);

}

}

 

[다차원 배열]

-10 X 10 정수 랜덤 데이터 생성하여 전체 데이터 분석

public class Main {



public static void main(String[] args) {



int N = 50;

int[][] array = new int[N][N];

for(int i = 0; i< N; i++) {

for(int j=0 ; j< N; j++) {

array[i][j] = (int) (Math.random()* 10);

}

}

for(int i=0; i<N; i++) {

for(int j=0; j<N; j++) {

System.out.print(array[i][j] + "");

}

System.out.println();

}

 

[클래스]

-하나의 점을 의미하는 Node클래스 생성

public class Node {



//필드

private int x;

private int y;



//생성자

public Node(int x, int y) {

this.x = x;

this.y = y;

}



//메소드

public int getx() { //getter()메소드 이용

return x;

}

public void setx(int x) { //setter() 메소드 이용

this.x = x;

}

public int gety() { //getter()메소드 이용

return y;

}

public void sety(int y) { //setter() 메소드 이용

this.y = y;

}



public Node getCenter(Node other) {

//다른 Node 가져와서 정중앙지점을 Node타입으로 반환 메소드



return new Node((this.x + other.getx()) / 2 , (this.y + other.gety() / 2)) ; //두 Node의 정 중앙점을 반환



}

}

-Node 클래스 이용하여 두 점 사이 중점 구하기



public class Main {



public static void main(String[] args) {



Node one = new Node(10, 20);

Node two = new Node(30, 40);

Node result = one.getCenter(two);

System.out.println("x : " + result.getx() + "y : " + result.gety() );

}

}

 

[상속] : 클래스 간의 상호작용

 

-하나의 사람을 의미하는 Person클래스 생성

import Tutorial.Node;



public class Person { //부모 클래스

//필드

private String name;

private int age;

private int height;

private int weight;



//생성자

public Person(String name, int age, int height, int weight) {

super(); //부모 생성자 자동 생성

this.name = name;

this.age = age;

this.height= height;

this.weight = weight;

}



//소스 -> getter/setter 메소드 생성

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public int getAge() {

return age;

}

public void setAge(int age) {

this.age = age;

}

public int getHeight() {

return height;

}

public void setHeight(int height) {

this.height = height;

}

public int getWeight() {

return weight;

}

public void setWeight(int weight) {

this.weight = weight;

}



}

 

-Person을 상속받는 하나의 학생 Studend 클래스 생성

public class Student extends Person {

//자식 클래스의 자체 필드

private String studentID;

private int grade;

private double GPA;//학점



//생성자

public Student(String name, int age, int height, int weight, String studentID, int grade, double GPA) {



super(name, age, height, weight); //부모의 생성자 호출하여 부모 것도 가져옴

this.studentID = studentID;

this.grade = grade;

this.GAP = GAP;



}



//get,set() 메소드

public String getStudentID() {

return studentID;

}



public void setStudentID(String studentID) {

this.studentID = studentID;

}

public int getGrade() {

return grade;

}

public void setGrade(int grade) {

this.grade = grade;

}

public double getGPA() {

return GPA;

}

public void setGPA(double gPA) {

GPA = gPA;

}



//메소드

public void show() {

System.out.println("------------------------------------");

System.out.println(getName());

System.out.println(getAge());

System.out.println(getHeight());

System.out.println(getWeight());

System.out.println(getGrade());

System.out.println(getStudentID());

System.out.println(getGPA());

}





-Main클래스 작성



public class Main {



public static void main(String[] args) {



Student student = new Student("홍길동", 20, 175, 70, "20183041", 1, 4.5);

student.show();



}



}



}

 

[추상]

: 자바에서는 일종의 미완성 클래스인 추상 클래스를 제공한다. 기본 토대를 설계해두는 클래스이다. 실체 클래스들의 공통 특성을 설계, 구현해두는 클래스이다.

-추상의 개념을 이용하여 음악 플레이어 클래스 구현

-추상의 개념을 이용하여 응용 클래스 구현

public abstract class Player { //추상 클래스

public abstract void play(String songName); //곡이름 매개값 받아 실행 메소드



public abstract void pause(); //일시 정지 메소드



public abstract void stop(); //완전 정지 메소드



//메소드도 추상 메소드 : abstract붙은 메소드의 선언부만 있고 실행내용{}이 없는 메소드

//추상클래스 상속받은 실체 자식 클래스에서 반드시 추상 메소드 재정의해야만 함



}

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

public class Music extends Player{ //실체 메소드



@Override

public void play(String songName) {

System.out.println(songName + "곡을 재생합니다.");



}



@Override

public void pause() {

System.out.println("곡을 일시정지합니다.");



}



@Override

public void stop() {

System.out.println("완전히 정지합니다.");



}

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

public class Main { //실행 main 메소드



public static void main(String[] args) { //메인 메소드 작성



//재정의한 메소드 호출방식 -1. 객체 생성 후, 상속받은 자식타입 변수로 메소드 호출



Music music = new Music(); //실체 객체 생성해야 사용 O



music.play("내사람-SG워너비 ");

music.pause();

music.stop();

System.out.println("------------------------------------------");



//재정의 메소드 호출방식 –2.

부모타입 변수에 자식객체 연결해서 부모타입변수로 재정의 메소드 호출

Player player = new Music();

player.play("라라라-SG워너비 " );

player.pause();

System.out.println("------------------------------------------");



//-3) 호춯

MusicPlay(new Music());

System.out.println("------------------------------------------");

}



//재정의 메소드 호출방식 –3.

메소드의 매개변수를 부모타입으로 선언해두고 매개값에 자식 객체 대입시키면 자동으로 타입변환되어 재정의 메소드 호출됨



public static void MusicPlay (Player player) { //추가 메소드 작성

player.play("timeless-SGwannabe");

player.pause();

player.stop();

}

[final 키워드]

final 변수(필드) : 상수 , 이후 필드값 변경 불가

final 메소드 : 이후 메소드 재정의 불가

final 클래스 : 이후 클래스 상속 불가

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

[인터페이스]

: 클래스는 다중상속이 안되지만 인터페이스는 다중 상속 가능함

: 추상 클래스는 추상메소드 외에도 멤버 변수, 일반 메소드를 가질 수 있지만,

인터페이스는 반드시 사전에 정의된 추상메소드의 상수 + 추상메소드만 가질 수 있다.

- 인터페이스를 선언하고 메소드 다루기

인터페이스의 다중 상속

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

public interface Dog { //인터페이스 (1)



public abstract void crying(); //추상 메소드만 작성 O 일반 메소드 작성 X



public void show(); //컴파일과정에서 자동 abstract 붙여 인식함



public void One();



}

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

public interface Cat { //인터페이스 (2)



public abstract void crying(); //추상 메소드만 작성 O 일반 메소드 작성 X



public void show(); //컴파일과정에서 자동 abstract 붙여 인식함



public void two();

}

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

public class Main implements Dog, Cat { //인터페이스 다중 상속받아 구현한 구현 클래스



public static void main(String[] args) { //main 메소드



Main main = new Main(); //사용 위해 객체 생성

main.crying();

main.show();



}



//인터페이스의 추상 메소드 모두 구현



@Override

public void crying() {



System.out.println("월 월 ");



}



@Override

public void show() {



System.out.println("Hello World");



}



@Override

public void two() { //인터페이스 Dog의 메소드 재정의





}



@Override

public void One() { //Cat의 메소드 재정의



}

 

[다형성]

: 다양한 형태로 구현 가능해지는 성질

: 부모 클래스타입의 참조변수로 하위 클래스 객체를 참조할 수 있게 해주어 다형성 구현

: 타입변환 성질 이용 O

과일 정보 프로젝트 구현

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

public class Fruit { //부모 클래스



//필드 정의

String name;

int price;

int fresh;



public void show() { //메소드 정의

System.out.println("과일 이름 : " + name);

System.out.println("과일 가격 : " + price);

System.out.println("과일 신선도 : " + fresh);

}



}

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

public class Peach extends Fruit{ //자식 클래스



//변수 초기화 생성자 속에 기본초깃값 넣어줌 -> 앞으로 복숭아 객체 생성 시 기본값 채워져있음

//VS 생성자(매개값) 으로 정의해두면 객체 생성 시 넣은 매개값으로 생성된 객체 내부 값 채워질 거야



public Peach() {

price = 1500;

name = "복숭아";

fresh = 75;

}

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

}public class Banana extends Fruit{



public Banana() {

price = 1000;

name = "바나나";

fresh = 60;

}

}

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

import java.util.*;



public class Main {



public static void main(String[] args) {



Scanner sc = new Scanner(System.in); // 키보드 입력값에 따라 출력 다르게 하기

System.out.println("바나나 : 1 , 복숭아 : 2 ");

int input = sc.nextInt(); //입력받은 값



Fruit fruit; //일단 부모 타입 변수 선언

if(input == 1) {

fruit = new Banana(); //바나나 객체 연결

fruit.show();

}

else if (input == 2) {

fruit = new Peach(); //복숭아 객체 연결

fruit.show();

}

else {

System.out.println("잘못 입력 ");

}



//-----------------------------------------------------------

Fruit f1 = new Peach(); //부모타입에 자식 객체 생성 연결해서 넣어주면 다형성 O

f1.show();



Fruit f2 = new Banana();

f2.show();

}



}

 

[Object 클래스]

: 자바 최상위 클래스, 모든 클래스의 조상(부모)클래스

: 모든 클래스가 공통으로 포함하고 있는 기능을 가장 기본적으로 내부에 정의해둔 클래스

 

-객체 비교하는 방법 알아보자

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

public class Archer { //부모 클래스

//field

String name;

String pour;



//생성자

public Archer(String name, String pour) { //객체 생성 시 받은 매개값으로 내부 필드값 채워져서 생성될 거임

this.name = name;

this.pour = pour;

}

//메소드



public boolean equals(Object obj) { //부모타입으로 매개변수 선언해둠 -매개값으로 들어온 객체와 비교



Archer temp = (Archer) obj; //들어온 객체 일단 강제타입변환시켜놓고



if(name == temp.name && pour == temp.pour) { //내부 필드값 모두 동일하다면

return true; //T값 리턴

}

else {

return false; //F값 리턴

}

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

public class Main {



public static void main(String[] args) {



Archer ar1 = new Archer("궁수1", "상");

Archer ar2 = new Archer("궁수1", "상");



System.out.println(ar1 == ar2); //F값 반환함

//내부값 같더라도 각각 참조하는 변수가 다른 객체로 생성되었기 때문에 == 번지는 다른 객체



System.out.println(ar1.equals(ar2)); //T값 반환

//실제로 다른 객체일지라도 내부값을 비교하는 메소드이기 때문에. equals() 메소드는 내부값 비교 메소드



}

 

[객체지향의 활용]

게임 캐릭터 공격 프로젝트 구현

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

public class Hero { //히어로 캐릭터 부모클래스



//필드

String name;



//생성자

public Hero(String name) {

this.name = name;

}



//메소드

public void attack() { // 모든 캐릭터 기본 가진 공격성 정의해둠

System.out.println("주먹 찌르기 ");

}



}

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

public class Warrior extends Hero {



public Warrior(String name) {

super(name); //super는 부모클래스에게 상속받은 부모클래스의 필드 초기화 생성자 호출하여 초기화

}



public void groundCutting() { //상속 메소드 외에 해당 클래스가 가지는 특정 공격성은 자체 메소드로 추가



System.out.println("돼지 가르기");

}

}

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

public class Archer extends Hero {

//생성자

public Archer(String name) {

super(name);

}



//자체 메소드 추가

public void fireArrow() {

System.out.println("불화살");

}

}

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

public class Wizard extends Hero {

//생성자

public Wizard(String name) {

super(name);

}

//자체 메소드 추가



public void freezing() {

System.out.println("얼리기");

}

}

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

public class Main {



public static void main(String[] args) {



Hero[] heros = new Hero[3]; //캐릭터 3개 넣을 배열 생성

//배열 내부값에 각 객체 생성자 연결해서 초기화해둠

heros[0] = new Warrior("전사");

heros[1] = new Archer("궁수");

heros[2] = new Wizard("마법사");



for(int i = 0; i<heros.length; i++) { //배열 돌면서 각 배열 연결된 객체에 대하여



heros[i].attack(); //기본 공격 호출



if(heros[i] instanceof Warrior) { //만약 지금 객체 타입이 Warrior라면

Warrior temp = (Warrior) heros[i]; //일단 강제타입변환 시킨 뒤

temp.groundCutting(); //해당 타입의 특징 메소드 호출

}else if(heros[i] instanceof Archer) {

Archer temp = (Archer) heros[i];

temp.fireArrow();

}else {

Wizard temp = (Wizard) heros[i];

temp.freezing();

동빈나로 Java 다시 정리.hwp
0.06MB

728x90

'Java > [문법]_Java(자바)' 카테고리의 다른 글

ch14. 입출력 스트림  (0) 2021.08.24
ch13. 컬렉션 프레임워크  (0) 2021.08.23
ch12. 스레드  (0) 2021.08.23
11-1. java.lang 패키지  (0) 2021.08.11
ch10. 예외 처리  (0) 2021.08.05