데일리로그C:
article thumbnail
Published 2023. 1. 10. 16:47
230110_참조, 배열, 객체, 필드 JAVA/jsp

<1교시 ch05>

[거래내역]

package ex01;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Q07_1 {

	public static void main(String[] args) {
		boolean run = true;
		int balance = 0;  // 잔고
		Scanner sc = new Scanner(System.in);
		String order = "";  // 거래내역
		List<String> list = new ArrayList<String>();
		
		while(run) {
			System.out.println("--------------------");
			System.out.println("1.예금 2.출금 3.거래내역 4.종료");
			System.out.println("--------------------");
			
			System.out.print("선택> ");
			String menu = sc.nextLine();
			
			
			if(menu.equals("1") || menu.equals("예금")) { //1. 예금
				System.out.print("예금액> ");
				int deposit = Integer.parseInt(sc.nextLine());
				balance += deposit;
				order += "예금: " + deposit + "\n";  // 거래내역(문자열 저장)
				list.add("예금: " + deposit); // 거래내역(객체에 목록형태로 저장)
			} else if(menu.equals("2") || menu.equals("출금")) { // 2. 출금
				System.out.print("출금액> ");
				//balance -= Integer.parseInt(sc.nextLine());
				int price = Integer.parseInt(sc.nextLine()); // 원하는 출금액
				if(balance >= price) { // 잔고보다 작거나 같으면
					balance -= price; // 입력한 출금액 출력
					order += "출금: " + price + "\n";   // 거래내역
					list.add("출금: " + price); // 거래내역
				} else {
					System.out.println("출금이 불가능합니다."); // 아니라면 불가능 출력
				}
			} else if(menu.equals("3") || menu.equals("거래내역")) { // 3. 거래내역
				System.out.println("잔고>\n"+order);   // 거래내역
				System.out.println("=======================");
				for(String str : list) { // 향상된 for문 (list 객체를 str로 쪼개겠다)
					System.out.println(str);
				}
				
			} else if(menu.equals("4") || menu.equals("종료")){ // 4. 종료
				System.out.println("프로그램 종료");
				break;
			} else {
				System.out.println("존재하지 않는 메뉴입니다. 다시 선택하세요");
			}
		}
	}
}



* 자바에서 배열은 자리를 정해야함
List + ctrl + 스페이스바 --> List<String>

List = new ArrayList  : 객체를 객체로 묶어서

 

 

메모리 영역

  --> hip : 객체, 배열 생성

  --> Stack :  주소값, 

<ex> Stack hip
int a =1 1  
int b =2 2  
String c = "ab" 주소값 a(참조)
    b(참조)

 

참조타입의   == , != 연산 ---> 값이 아닌 주소값으로 비교

null : 힙 영역 객체를 참조하지 않는다는 뜻  (null 로 초기화는 가능하지만 제대로된 값은 아님)

NullPointerException : 초기화해라, 객체를 참조해라 라는 의미

 

package ex01;

public class Page167 {

	public static void main(String[] args) {
		char v1 = 'A';  // 문자타입으로 선언 및 초기화(= 변수)
		
		if(v1 == 'A') {  // if문 빠져나오게 되면 지역변수가 메모리에서 사라짐
			int v2 = 100;
			double v3 = 3.14;
		}
		
		boolean v4 = true;  // 최종 메모리에 남아있는 건 v1, v4임
		
		int[] s = {10,20,30};// S 라는 객체에 배열형태로 정수타입으로 담기
		// s.length = 3 
		
		/*
		int[] intArray = null; // 객체, null로 초기화 가능  
		System.out.println(intArray); //--> NullPointerException 발생
		intArray[0] = 10; 
		*/
		
		////page173 세개다 값은 같음. 주소값은 다름(s1 = s2 != s3)
		String s1 = "홍길동";
		String s2 = "홍길동";
		String s3 = new String("홍길동");
		
		if(s1 == s2) { //주소값 비교(참조)
			System.out.println("참조가 같다(주소값이 같다)");
		} else {
			System.out.println("참조가 다르다(주소값이 다르다)");
		}
		
		if(s1.equals(s2)) {
			System.out.println("값은 같다");
		}
		
		int aa = 1; // aa-stack(1) 주소값 가지지 않고 값을 전달함
		int bb = aa; // bb-stack(1)
		

	}

}


<2교시>

String : 생성자       !=     string : 변수

* 객체에선 null이 아닌 " " 로 하기

* 메소드 안에 메소드 만들기 X

 

배열

1) 선언  : 데이터타입[ ] 변수;  or 데이터타입 변수[ ];     * 이미 선언한 후에는 다른 실행문으로 초기화 못함

2) 초기화 : 데이터타입[ ] 변수 = 값;  or 데이터타입 변수[ ] = 값;

3) 생성

   - 값 목록 이용 : 데이터타입[ ] 변수 = { 값1, 값2, ............};

   - new  연산자 이용 :  데이터타입[ ] 변수 = new 데이터타입[길이] ;

       ㄴ> ex) 길이(=방 개수) :  5개  index[0] ~ index[4]로 구성  ( 길이 : 배열변수.length   "객체만" 사용)

       ㄴ> 변수[인덱스] = 값; 으로 대입

 

<3교시 변수 참조배열>

자바에선 배열 은 배열로 / int는 int로 


각 리턴타입마다 매개변수 달라짐

1. public : 

2. static : 정적 메소드 (객체 활용하지않고 함수를 이용해서)
  ㄴ> 필수로 적어야함 [ Test01 ]

3. void : return 할 값이 없음을 의미(실행만 해라)
  ㄴ> String : 문자열 값을 반환
  ㄴ>  int : 숫자(정수) 값을 반환

main 함수는 기본적으로 실행시킴(이미 만들어진 함수라서 내재되어있음)

만든 함수는 실행구문 필요함. 

 

package ex01;

public class Page180 {

	public static void main(String[] args) {
		String name[] = {"이", "박","김"};   // 첫번째
		String[] name1 = {"이", "박","김"};  // 두번째
		
		System.out.println(name[0]);
		System.out.println(name[1]);
		System.out.println(name[2]);
		
		for(int i=0; i<=name.length; i++) {
			// name[i] = ""+i;  문자열로 형변환
			System.out.println(name[i]); // 출력구문 
		}
		
		String names[] = new String[] {"이", "박","김"};  //세번째
		
		
		

	}
}

 

package ex01;

public class Page182 {

	public static void main(String[] args) {
		int s[] = new int[] {83,90,87}; // 변수 = 값 : 매개변수
		int sum = 0; // 전역변수
		for(int i = 0; i<s.length;i++){
			sum +=s[i];
		}
		System.out.println(sum);  //260
		
		///////////////////////////
		int sum2 = add(new int[] {83,90,87});  // 위에껄 add라는 함수로 만들어 int 변수에 담기
		System.out.println(sum2); // 260
	 }
	
	
	public static int add(int s[]) { // 배열로 보냈으니 배열로 받기
		int sum = 0;
		for(int i=0; i<s.length; i++) {
			sum += s[i];
		}
		return sum;

	}

}

 

package ex01;

public class Page183 {

	public static void main(String[] args) {
		int[] s = new int[3];  //방부터 만들기(길이 먼저 선언하기)  s.length =3
		s[0] = 10;
		s[1] = 10;
		s[2] = 10;
		//s[3] = 10;   [3] 개수와 일치하지 않아서 오류발생
		
		System.out.println(s.length);
		
	}

}

 

package ex01;

public class Page190 {

	public static void main(String[] args) {
		int [][] s2 = {{1,2,3},{4,5,6}}; // 초기화
			
		// s[0].length;   첫번째 층의 방의 개수
		// s[1].length;   두번째 층의 방의 개수
		
		for(int i=0; i<s2.length; i++) {  // 층의 개수
			for(int j=0; j<s2[i].length; j++) { // 방의 개수
				System.out.print(s2[i][j]+"\t");
			}
			System.out.println();
		}
		
		///////////////////////////////
		
		int[][] s1 = new int[2][3]; // 방 크기 선언 [층 0,1][방 0,1,2]
		/* 아래처럼 형식 구성되게 
		s1[0][0] = 1;
		s1[0][1] = 2;
		s1[0][2] = 3;
		s1[1][0] = 4;
		s1[1][1] = 5;
		s1[1][2] = 6;
		*/
		
		int num =1;
		for(int i=0; i<s1.length; i++) {  // 층의 개수
			for(int j=0; j<s1[i].length; j++) { // 방의 개수
				s1[i][j] =num;
				System.out.print(s1[i][j]+"\t");
				num++;
			}
			System.out.println();
		}

	}

}

 

package ex01;

public class Test01 {

	public static void main(String[] args) { // main 메소드 안에 메소드 만들수 없음
		int x = 1;
		int y = 2;
		int result = x+y;
		System.out.println(result);  // 3
		///////////////////
		
		Test01 t = new Test01(); // static 없다면 적어야함
		t.abc(1, 2);  // 객체로 만들어서 메소드 사용해야함
		
		abcd(1,2); // 값의 수 = 매개변수 수 동일해야함 (실행시키기 위해 필요함)

	}
	// 동적 메소드
	public void abc(int x, int y) {  // abc 함수 생성
		// return;   --> void이므로 없음
		int result = x + y;
		System.out.println(result);  // 3
	}
	
	// 정적 메소드
	public static void abcd(int x, int y) {  // abc 함수 생성
		// return;   --> void이므로 없음
		int result = x + y;
		System.out.println(result);  // 3
	}
	

}



<4교시>

객체 참조 배열 --> String

향상된 for문  :  for(String 변수명 : 큰 객체) {  }   

  --> 배열에만 사용

  --> 큰 개념에서 작은 단계로 쪼갤 때 사용

  --> 반복횟수 : 배열의 항목 수

 

package ex01;

import java.util.List;
import java.util.Vector;

public class Page198 {

	public static void main(String[] args) {
		// 일반적인 for구문
		int[] s = {90,80,70};
		int sum = 0; // 전역변수
		for (int i=0; i<s.length; i++) {
			sum+=s[i];
		}
		System.out.println(sum);  //240
		
		///////////////////////////////
		//향상된 for구문
		sum=0;
		for(int num : s) {  // 타입변수 : 배열 (배열객체s를 int로 쪼개서 출력하자)
			System.out.println(num);  // 90,80,70
			sum += num;
		}
		System.out.println(sum);  //240
		
		/////////////////////////////////
		//List<String> str = new Vector<>(); 뒤에 string 생략 가능
		List<String> str = new Vector<String>(); // string 타입을 list화 하겠다
		str.add("a");
		str.add("b");
		for(String ss : str) {
			System.out.println(ss);
		}
	}

}



<5교시>

for문-배열
 ㄴ> 조건식에 i < 변수명.length 를 사용할 것

for ( int i = 0 ; i < 변수명.length ; i++ ) {

}

 

[p200 Q03]

package ex01;

public class Q03 {

	public static void main(String[] args) {
		int[][] aa = {
				{95,86},
				{83,92,96},
				{78,83,93,87,88}
		};
		// 각 층의 합을 출력하시오
		int sum = 0;
		for(int i =0; i<aa.length; i++) {
			for(int j=0;j<aa[i].length; j++) {
				//
			}
		}
		
		
		/* t 답
		int[] total = new int[aa.length]; // 합
		
		for(int i=0; i<aa.length; i++) {
			for(int j=0; j<aa[i].length; j++) {
				if(i==0) {
					total[0] += aa[0][j];
				} else if(i==1) {
					total[1] += aa[1][j];
				} else if(i==2) {
					total[2] += aa[2][j];
				}
			}
			System.out.println("총합: " + total[i] + ", 평균값: " + (total[i]/aa[i].length));
		}
		*/
		
		
		// 각 층의 평균값을 출력하시오
	}

}

 

[p200 Q04]

package ex01;

public class Q04 {

	public static void main(String[] args) {
		int max = 0; // 전역변수
		int min = 10;
		int aa[] = {1,5,3,8,2};
		
		// max 구현
		for(int i=0; i<aa.length; i++) {
			if(max < aa[i]) { // 전역변수 max가 aa[i] 값보다 작다면
				max = aa[i];  // 지역변수 max에 aa[]값을 대입
			} 
			// min 구현
			if(min > aa[i]) {
				min = aa[i];
			}	
		}
		System.out.println("max: " + max);  //8
		System.out.println("min: " + min); //1
	}
}

 

[p201 Q05]

package ex01;

public class Q05 {

	public static void main(String[] args) {
		int[][] aa = {
				{95,86},
				{83,92,96},
				{78,83,93,87,88}
		};
		
		int sum = 0;
		double avg = 0.0;
		int num=0;  // 전체 방 개수 전역변수
		
		//작성
		for(int i=0; i<aa.length; i++) {
			for(int j=0; j<aa[i].length; j++) {
				sum+=aa[i][j];  // sum = sum + aa[i][j];
				num++;    // num += aa[i].length;
				
				avg= sum/(double)num;
			}
		}
		System.out.println("sum: "+sum);  //881
		System.out.println("avg: "+avg);  //88.1
	}
}

 

[p201 Q06]

package ex01;

import java.util.Scanner;

public class Q06 {

	public static void main(String[] args) {
		boolean run = true;
		int num = 0; // 학생수
		int[] scores = null; // 점수
		Scanner sc = new Scanner(System.in);
		
		while(run) {
			System.out.println("--------------------------");
			System.out.println("1.학생수 2.점수입력 3.점수리스트 4.분석 5.종료");
			System.out.println("--------------------------");
			System.out.print("선택> ");
			
			int selectNo = Integer.parseInt(sc.nextLine());
			
			if(selectNo ==1) {
				System.out.print("학생 수> ");
				num += Integer.parseInt(sc.nextLine());
				scores = new int[num];  // 점수 업데이트 (null 값이면 오류뜸)
			} else if(selectNo==2) {
				for(int i=0; i<num; i++) {
					System.out.print("scores["+ i+"]> ");
					scores[i] = Integer.parseInt(sc.nextLine());
				}
			} else if(selectNo==3) {
				for(int i=0;i<num;i++) {
					System.out.println("scores["+ i+"]> " + scores[i]);
				}
			} else if(selectNo==4) {
				int max =0;
				int sum =0;
				double avg =0;
				for(int i=0; i<num; i++) {
					sum+= scores[i];
					
					if(max<scores[i]) {
						max = scores[i];
					}
					
					avg = sum/(double)num;
					
				}
				System.out.println("최고점수: " + max);
				System.out.println("평균점수: " + avg);
				
			} else if(selectNo==5) {
				run = false;
			} 
		}
		System.out.println("프로그램 종료");

	}

}

 

<6교시 ch06 >

<공부 순서>
jsp, 변수, 객체  --> 1project
model1 (java)  --> 책 
model2 MVC 패턴   --> 2project
spring

 

클래스 : 설계도
인스턴스 : 객체

 

<7교시>

* Student 클래스에 있는 변수 --> StuTest에선 속성이 됨

 

클래스
1. 라이브러리용 (ex) Car.java
1) 필드 : 데이터 저장  
   --> int, String, 등등
   --> 우클릭 > source > Generate getters and setters   ( set : 입력 / get : 출력 )
   --> 우클릭 > source > Generate toString( )

2) 생성자 : 초기화
   --> 기본생성자이므로 생략 가능, 클래스이름, 리턴X, 대문자

3) 메소드 : 실행, 동작


2. 실행용 (ex) CarTest.java

 

1) 필드

  --> 선언 : 타입 필드명 = 초기값; 

 

분류 타입 초기값
기본타입 정수 byte  char short int long 0
실수 float double 0.0
논리 boolean false, true
참조타입 배열, 
클래스(String),
인터페이스
null

[p219 예제]

package ex01;

public class Student {  // 기본생성자라 생략되어있음
	// 라이브러리 클래스
	
	String name; // 이름 (변수) --> 속성
	int grade; // 학년 (변수)
	int age; // 나이
	

	void aaa() {
		System.out.println("이쁘다");  // (함수) 여자
	}
	
	void bbb() {
		System.out.println("잘생겼다");  // (함수) 남자
	}

}

 

package ex01;

public class StuTest {

	public static void main(String[] args) {
		int a = 1;
		String s = new String("홍길동");  //객체
		Student yj = new Student();  // new 연산자 + 기본 생성자 를 이용해 객체 생성
		yj.name = "예진";
		yj.grade = 1;
		yj.age = 25;
		System.out.println(yj.grade + "학년 " + yj.name);
		yj.aaa();

	}

}

 

package ex01;

public class StudentExample {
	// 실행 클래스

	public static void main(String[] args) {
		Student s1 = new Student(); // 각각의 이름, 학년, 나이 등의 값 가짐
		Student s2 = new Student();
		
		Member m = new Member();
		m.id = "1234";
		
		System.err.println(m.toString());

	}

}

 

package ex01;

public class Member {

	// 필드
	String id;
	String pass;
	String name;
	int age;
	int tall;
	int kg;
	String email;
	String phone;
	String address;
	String zipcode;
	boolean a;
	
	
	// 생성자 --> 생략
	
	// 
	
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getPass() {
		return pass;
	}
	public void setPass(String pass) {
		this.pass = pass;
	}
	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 getTall() {
		return tall;
	}
	public void setTall(int tall) {
		this.tall = tall;
	}
	public int getKg() {
		return kg;
	}
	public void setKg(int kg) {
		this.kg = kg;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public String getZipcode() {
		return zipcode;
	}
	public void setZipcode(String zipcode) {
		this.zipcode = zipcode;
	}
	public boolean isA() {
		return a;
	}
	public void setA(boolean a) {
		this.a = a;
	}
	
	@Override
	public String toString() {
		return "Member [id=" + id + ", pass=" + pass + ", name=" + name + ", age=" + age + ", tall=" + tall + ", kg="
				+ kg + ", email=" + email + ", phone=" + phone + ", address=" + address + ", zipcode=" + zipcode
				+ ", a=" + a + "]";
	}
	
}

 

package ex01;

public class Car {
	
	// 필드
	String company = "현대자동차";
	String model = "그랜저";
	String color = "검정";
	int maxSpeed = 350;
	int speed;
	
	@Override
	public String toString() {
		return "Car [company=" + company + ", model=" + model + ", color=" + color + ", maxSpeed=" + maxSpeed
				+ ", speed=" + speed + "]";
	}
	
	
}

 

package ex01;

public class CarTest {

	public static void main(String[] args) {
		// 객체생성
		Car c = new Car();
		
		/*
		System.out.println(c.company);
		System.out.println(c.model);
		System.out.println(c.color);
		System.out.println(c.maxSpeed);
		System.out.println(c.speed);
		*/
		
		// 필드 변경
		c.speed = 60;
		
		System.out.println(c.toString()); // 위와 동일한 기능임
		
	}

}

 

[p230 Q02]

package ex01;

public class Member2 {

	String name;
	String id;
	String password;
	int age;
	
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	
	@Override
	public String toString() {
		return "Member2 [name=" + name + ", id=" + id + ", password=" + password + ", age=" + age + "]";
	}
	
	
}

 

package ex01;

public class Member2Test {

	public static void main(String[] args) {
		Member2 m = new Member2();
		
		m.id = "1234";
		System.out.println(m.toString());
		System.out.println(m.id);
		
		m.setId("5678");
		System.out.println(m.toString());
		System.out.println(m.getId());
		
		m.name = "최하얀";
		m.age = 23;

	}

}
profile

데일리로그C:

@망밍

포스팅이 도움됐다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!

profile on loading

Loading...