본문 바로가기
코딩/수업 정리

20.12.02 Wed [008]

by 6^6 2020. 12. 2.
728x90
  • 참조변수에 null대입
  • 생성자와 String 클래스
  • 생성자 함수
  • 디폴트 생성자
  • 입력
  • 클래스 이름 규칙
  • 오늘의 문제

*상식 : initialization= 초기화(변수,클래스 이름만들때 init~~이라고 쓰기도함)

참조변수에 null대입

BankAccount ref = new BankAccount(); //ref가 참조변수

......  ref=null; //ref 가 참조하는 인스턴스와의 관계를 끊음.

 

BankAccount ref = null; //참조변수안에 null을 넣는것. - 초기화한거임.

if(ref ==null) //

 

null체크를 안해서 생긴 에러코드

//null체크를 안해서 생긴 에러코드
public class RecMain {

	public static void main(String[] args) {
		//Rectangle rec; 이것보다 ↓밑에코드가 더 좋다.
      	  Rectangle rec = null; //rec가 주소값을 아무것도 가르키지 않고 있다는 상태.
		
		rec.getHeight();
	}
}
/*Exception in thread "main" java.lang.NullPointerException: 
  Cannot invoke "java_rec.Rectangle.getHeight()" because "rec" is null
	at java_rec/java_rec.RecMain.main(RecMain.java:7)*/ //이런 오류남

(블로그 참조) java.lang 패키지 안에 있는 클래스인 Rectiangle의 참조변수인 rec가 null값을 가지니 intValue()를 불러오는데 에러가 생긴 거다. 

 코드 rec null값이 아닌 다른 값을 이용하려고 하는데 null값이니 에러가 날 수 밖에 없는 것이다.

 

 

null에러 해결

//null에러 해결
public class RecMain {

	public static void main(String[] args) {
		Rectangle rec = null;
		
		if(rec != null)
		rec.getHeight();
	}
} //if문으로 null이 아니면  체크해줘야함!!!
//매개변수로 와야하는 것들 null체크 해야함 꼭!

 

 

String 클래스

:문자열 받는 클래스

public class World {
	public static void main(String[] args) {
		String str1 = "Happy"; //타입:String, 변수이름:str1, 참조형,4byte 주소가 옴.
		String str2 = "Birthday";//str에는 happy,birthday가 들어가는게 아니라 
        					//주소가 들어가는 것임.
		System.out.println(str1 + " "+str2);
		
		printString(str1);
		printString(str2);
	}
	
	public static void printString(String str){ //함수만듦-타입맞추기.
		System.out.println(str);
	}
}

 

 

생성자 함수

:초기화 메소드를 대신함

 

public static void main(String[] args) {
		Rectangle rec =  new Rectangle(); //new Rectangle에서 Rectangle이 생성자 함수
						//=클래스 이름과 똑같은 함수
						//=생성자함수(객체 생성할때 이렇게 씀)

생성자의 이용 의도는 초기화임.

 

디폴트 생성자

 

모든클래스의 생성자는 생성자호출을 불러온다

 

 

예제

public class World {
	public static void main(String[] args) {
		
		TV myTV = new TV("LG", 2017, 32); //TV라는 클래스를 만들어라
		myTV.show();
		
		Person kim = new Person("김철수",27); //Person이라는 클래스를 만들어라
		kim.printPerson();

		Song mySong = new Song("artist","ABBA",1974,"스웨덴");
		mySong.show();
       	
		Song mySong2 = new Song("이별공식","Ref",1992,"한국");
		mySong2.show();
        
	}
}//LG에서 만든 2017년 32인치
//이름 김철수,나이 27세
//1974년 스웨덴국적의 ABBA가 부른 artist
//1992년 한국국적의 Ref가 부른 이별공식
public class TV {
		String name;
		int year;
		int inch;
		
		TV(String name, int year, int inch) { //생성자만들기
			this.name = name;//파라미터와 이름이 똑같으면 this붙여준다.
			this.year = year;
			this.inch = inch;	
		}
	
	public void show(){
		System.out.println(name+"에서 만든 "+year+"년 "+inch+"인치")
	}
}
public class Person {
		String name; //데이터변수는 상식적으로 위에 와야한다!!
		int age;
       
	  /*public String getName(){ //(응용)이렇게 호출해도 가능!
			return name;
		}*/
		
		Person(String name, int age) { //생성자만들기
			this.name = name;//파라미터와 이름이 똑같으면 this붙여준다.
			this.age = age;
		}
	
	public void printPerson(){
		System.out.println("이름 "+name+",나이 "+age+"세");
	}
}
public class Song {
	String title;
	String artist;
	int year; 
	String country; 
	
	Song(String title, String artist, int year, String country){
		this.title = title;
		this.artist = artist;
		this.year = year;
		this.country = country;		
	}
	public void show(){
		System.out.println(year+"년 "+country+"국적의 "+artist+"가 부른 "+title);
	
	}	
}

만약 파라미터가 없으면 return값 있어야한다!

 

입력 - 현업에서 쓰일 일은 거.의.X

java.util

스캐너-입출력 (=키보드)

 

public class World {
	public static void main(String[] args) {
		
		Scanner scanner = new Scanner(System.in);
		System.out.println("숫자를 입력하세요");
		int num1 = scanner.nextInt();
		int num2 = scanner.nextInt();
		String name = scanner.next();
		System.out.println("당신이 입력한 숫자와 문자는? "+num1+" "+num2+" "+name);

		scanner.close();
        }
}

예제

package java_hello;

import java.util.Scanner;

public class CCC {

	public static void main(String[] args) {

		Scanner scanner = null;
		while (true) {
			scanner = new Scanner(System.in);
			int math, science, english;

			System.out.println("수학,과학,영어 점수 입력");
			math = scanner.nextInt();
			science = scanner.nextInt();
			english = scanner.nextInt();

			Grade me = new Grade(math, science, english);
			System.out.println("평균은" + me.average());

			System.out.println("계속 하시겠습니까?(Y/N)");
			String YesOrNo = scanner.next();

			if (YesOrNo.equals("Y") || YesOrNo.equals("y")) {
				continue;
			} else {
				break;
			}
		}
		System.out.println("프로그램을 종료합니다.");
		scanner.close();
	}
}

 

클래스이름규칙

클래스 첫글자는 대문자

상수이름은 대문자. 여러단어면 _로나누기 ex) final int RAINBOW_SHADOW

 

 

오늘의 문제

1.생성자란 무엇인가?

클래스 이름과 똑같은 함수.


2.디폴트 생성자란 무엇인가?

public 이름)

별도로 생성자를 선언하지 않은 경우 컴파일러에 의해 자동 삽입된다.

3.생성자의 용도에 대하여 설명하시오.

생성자의 용도는 초기화이다.

4.null 에 대하여 설명하시오.

값이 없다는 뜻이다.

ex) Rectangle rec = null;

rec가 주소값을 아무것도 가르키지 않고 있다는 상태.


5.금일 프로그래밍 했던 문제

자바 클래스를 작성하는 연습을 해보자. 다음 main() 메소드를 실행하였을 때 예시와 같이 출력되도록 TV 클래스를 작성하라.

 

문제1.

//문제1
public static void main(String[] args) {
   TV myTV = new TV("LG", 2017, 32); //LG에서 만든 2017년 32인치
   myTV.show();
}

내 답변

package java_Practice;

public class Main {
	public static void main(String[] args) {
		   TV myTV = new TV("LG", 2017, 32); 
		   myTV.show();
		}
}//LG에서 만든 2017년 32인치
package java_Practice;

public class TV {
	String brand;
	int year;
	int inch;

	TV(String brand, int year, int inch) {
		this.brand = brand;
		this.year = year;
		this.inch = inch;
	}

	public void show(){
		System.out.println(brand + "에서 만든 " + year + "년 " + inch + "인치");
	}
}

 

문제2.

//문제2
		int math, science, english;
		math = 90;
		science = 100; 
		english = 80;
		
		Grade me = new Grade(math, science, english);
		System.out.println("평균은 " + me.average());

 

내 답변

package java_Practice;

public class Grade {

	double math, science, english;

	Grade(double math, double science, double english) {
		this.math = math;
		this.science = science;
		this.english = english;

	}

	public double average() {
		return (math + science + english) / 3.0;

	}

}
package java_Practice;

public class Main {
	public static void main(String[] args) {
	
		int math, science, english;
		math = 90;
		science = 100; 
		english = 80;
		
		Grade me = new Grade(math, science, english);
		System.out.println("평균은 " + me.average());
		}
}//평균은 90.0

 

문제3.

//문제3
노래 한 곡을 나타내는 Song 클래스를 작성하라. Song은 다음 필드로 구성된다.

- 노래의 제목을 나타내는 title
- 가수를 나타내는 artist
- 노래가 발표된 연도를 나타내는 year
- 국적을 나타내는 country

또한 Song 클래스에 다음 생성자와 메소드를 작성하라.
- 생성자 2개: 기본 생성자와 매개변수로 모든 필드를 초기화하는 생성자
- 노래 정보를 출력하는 show() 메소드
- main() 메소드에서는 1978년, 스웨덴 국적의 ABBA가 부른 "Dancing Queen"을
song 객체로 생성하고 show()를 이용하여 노래의 정보를 다음과 같이 출력하라.

나의답

package java_Practice;

public class Main {
	public static void main(String[] args) {
	
		Song song = new Song("Dancing Queen","ABBA",1974,"스웨덴");
		
		song.show();
	}
}
package java_Practice;

public class Song {
	String title;
	String artist;
	int year;
	String country;

	Song(String title, String artist, int year, String country) {
		this.title = title;
		this.artist = artist;
		this.year = year;
		this.country = country;
	}

	public void show() {
		System.out.println(year + "년 " + country + 
				"국적의 " + artist + "가 부른 " + title);
	}
}//1978년 스웨덴국적의 ABBA가 부른 Dancing Queen

 

 

문제4.

//문제4
아래와 같이 성적을 연속적으로 입력 받고 평균을 내는  프로그램을 작성하시오.

국어 영어 수학을 입력하세요!
100 60 70
평균은 76.66666666666667
계속 하시겠습니까
y
국어 영어 수학을 입력하세요!
90 80 70
평균은 80.0
계속 하시겠습니까
n
프로그램 종료 입니다.

6. 아래의 프로그램을 작성하시오.


 - 화폐 매수 구하기
 - 반드시 클래스로 작성할것 
출력
---------------------------------
136000
오만원 : 2장
만원 : 3장
오천원 : 1장
천원 : 1장
오백원 : 0개
백원 : 0개
계속 하시겠습니까
y
1456000
오만원 : 29장
만원 : 0장
오천원 : 1장
천원 : 1장
오백원 : 0개
백원 : 0개
계속 하시겠습니까

package java_hello;

import java.util.Scanner;

public class World {
	public static void main(String[] args) {
		
		Scanner scanner = null;
		
		while(true) {
		Scanner scanner1 = new Scanner(System.in);
		int balance,num,m50000,m10000,m5000,m1000,m500,m100;
		balance = 0;
		num = 126500;
		m50000 = 50000;
		m10000 = 10000;
		m5000 = 5000;
		m1000 = 1000;
		m500 = 500;
		m100 = 100;
		
		num = scanner1.nextInt();

		balance = num/m50000;
		System.out.println("오만원:"+balance+"장");
		num -= balance*m50000;
		
		balance = num/m10000;
		System.out.println("만원:"+balance+"장");
		num -= balance*m10000;
		
		balance = num/m5000;
		System.out.println("오천원:"+balance+"장");
		num -= balance*m5000;
		
		balance = num/m1000;
		System.out.println("천원:"+balance+"장");
		num -= balance*m1000;
		
		balance = num/m500;
		System.out.println("오백원:"+balance+"장");
		num -= balance*m500;
		
		balance = num/m100;
		System.out.println("백원:"+balance+"장");
	

		System.out.println("계속하시겠습니까?");
			
		String yesOrno = scanner1.next();
		if(yesOrno.equals("Y")|| yesOrno.equals("y")) {
			continue;
		}else
			break;
		
		}
			System.out.println("프로그램종료");
			scanner.close();
	}
}

 

 

7.자바의 명명 규칙에 대하여 설명하시오.


-클래스

첫글자는 대문자로 ex) class Mouse 


-메소드와 변수

여러단어를 혼합하여 사용한다면 첫 번째 단어는 소문자,  두 번째 단어부터는 대문자로 시작

ex)firstName


-상수

모든 이름을 대문자로. 여러단어면 _로 나누기

ex) final int Mouse_Keyboard


-camel case

여러단어 혼합해서 쓸 때 단어마다 첫글자는 대문자로 쓴다

ex) FirstName

 

-snake case

여러단어 혼합해서 쓸 때 소문자 단어를 _으로 나누는것

ex)first_name

728x90

'코딩 > 수업 정리' 카테고리의 다른 글

20.12.04 Fri [010]  (0) 2020.12.04
20.12.03 Thu [009]  (0) 2020.12.03
참고하기 좋은 사이트  (0) 2020.12.01
20.12.01 Tue [007]  (0) 2020.12.01
20.11.30 Mon [006]  (0) 2020.11.30

댓글