| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| 8 | 9 | 10 | 11 | 12 | 13 | 14 |
| 15 | 16 | 17 | 18 | 19 | 20 | 21 |
| 22 | 23 | 24 | 25 | 26 | 27 | 28 |
| 29 | 30 | 31 |
Tags
- 설정
- 스프링
- Ajax
- 오류모음
- 오라클
- 무결성 제약조건
- 공부
- 백준문제
- jsp
- 파워서플라이
- for문
- 이클립스단축기
- 순환문
- 환경설정
- 깃허브 블로그
- MSI
- 백준문제풀이
- 티스토리 블로그
- 전화번호부
- ORA-01407
- spring
- 별 찍기
- ORA-02292
- 인터페이스
- while
- 백준
- 오류
- 자바
- Oracle
- 이클립스
Archives
- Today
- Total
danDevlog
Java - day 15 (11~13연습문제 / 예외처리) 본문
728x90
// 11장
public class ElevenPratice {
// 1번 : equals
// 2번 : a-> "abc" 메모리
// d -> "def" 메모리
// a -> "abcdef" 새로운 메모리
// 3번 : Wrapper
// 4번 : 밑에 MyDog코딩
// 5번 : class.forName()
public static void main(String[] args) {
MyDog dog = new MyDog("멍멍이", "진돗개");
System.out.println(dog.toString());
}
}
class MyDog{
String name;
String type;
public MyDog(String name, String type) {
// TODO Auto-generated constructor stub
this.name = name;
this.type = type;
}
@Override
public String toString() {
return type + " " + name;
}
}
// 12장
import java.util.HashSet;
public class TwelvePratice {
// 1번 : 컬렉션 프레임워크
// 2번 : 제네릭
// 3번 : Iterator
// 4번 : 정렬하기 위해서
// 5번 : 코딩
public static void main(String[] args) {
HashSet<Student> set = new HashSet<Student>();
set.add(new Student("100","홍길동"));
set.add(new Student("200","강감찬"));
set.add(new Student("300","이순신"));
set.add(new Student("400","정약용"));
set.add(new Student("100","송중기"));
System.out.println(set);
}
}
class Student {
String name;
String id;
public Student(String id, String name) {
// TODO Auto-generated constructor stub
this.name = name;
this.id = id;
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
return Integer.parseInt(id);
}
@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
if(obj instanceof Student) {
Student s = (Student) obj;
if(s.id.equals(id)) {
return true;
}else {
return false;
}
}
return false;
}
@Override
public String toString() {
return name + ":" + id;
}
}
import java.util.HashMap;
public class TwelvePratice2 {
public static void main(String[] args) {
CarFactory factory = CarFactory.getInstance();
Car sonata1 = factory.createCar("연수 차");
Car sonata2 = factory.createCar("연수 차");
System.out.println(sonata1 == sonata2);
Car avante1 = factory.createCar("승연 차");
Car avante2 = factory.createCar("승연 차");
System.out.println(avante1 == avante2);
System.out.println(sonata1 == avante1);
}
}
class Car{
String name;
public Car(String name) {
this.name = name;
}
public Car() {
// TODO Auto-generated constructor stub
}
}
class CarFactory{
private static CarFactory instance = new CarFactory();
private CarFactory() {
// TODO Auto-generated constructor stub
}
HashMap<String, Car> carMap = new HashMap<>();
// 맵의 키와 값의 쌍. String 은 키, Car 는 값.
public static CarFactory getInstance() {
// TODO Auto-generated method stub
if(instance == null) {
instance = new CarFactory();
}
return instance;
}
public Car createCar(String name) {
Car car;
if(carMap.containsKey(name)) {
// 주어진 이름과 일치하는 객체가 해쉬맵에 있는지?
return carMap.get(name);
}else {
car = new Car(); // 키가 중복되는 객체가 없다면, 생성
carMap.put(name, car); // 해쉬맵에 추가
}
return car;
}
}
// 13장
package marchTen;
interface Calc{
public int add(int num1, int num2);
}
public class ThirtyPractice {
// 1번 : final
// 2번 : 익명 내부 클래스
// 3번 : 람다식
// 4번 : 함수형 인터페이스
// 5번 : 코딩
// 6번 : 스트림
// 7번 : 코딩
public static void main(String[] args) {
Calc sum = (x,y) -> x + y;
System.out.println(sum.add(10, 20));
}
}
import java.util.ArrayList;
import java.util.List;
public class ThirtyPractice2 {
public static void main(String[] args) {
List<Book> bookList = new ArrayList<>();
bookList.add(new Book("자바", 25000));
bookList.add(new Book("파이썬", 15000));
bookList.add(new Book("안드로이드", 30000));
int totalPrice = bookList.stream().mapToInt(b->b.getPrice()).sum();
System.out.println("모든 책의 가격 : " + totalPrice);
// 2만원 이상의 결과만 표시
bookList.stream().filter(b -> b.getPrice() >= 20000).map(b -> b.getName()).
sorted().forEach(s -> System.out.println(s));
}
}
class Book{
private String name;
private int price;
public Book(String name, int price) {
// TODO Auto-generated constructor stub
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
자주 보이는 오류 모음
FileNotFoundException : 파일을 못 찾는다.
SocketException : 동기화 처리.
동기화 : 전화기. 동일한 시간 타이밍.
비동기화 : 무전기.
ArithmeticException : 수학적 예외. 0을 나눌수 없죠?
IndexOutofBoundsException : 배열의 범위를 벗어낫을때,
NullPointerException : 객체가 널인데, 관련 메소드 호출할때.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Main {
// trt catch finally 예제
public static void main(String[] args) {
FileInputStream fis = null;
try {
fis = new FileInputStream("a.txt");
} catch (FileNotFoundException e) {
System.out.println(e);
return;
}finally{
if(fis != null){
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("항상 수행 됩니다.");
}
System.out.println("여기도 수행됩니다.");
}
}
package marchTen;
// 한 바이트씩 읽기
import java.io.FileInputStream;
import java.io.IOException;
public class FileInputStreamEx {
public static void main(String[] args) {
FileInputStream fis = null;
try {
fis = new FileInputStream("./input.txt");
System.out.println((char)fis.read()); // 영어 1문자씩 a
System.out.println((char)fis.read()); // b
System.out.println((char)fis.read()); // c
} catch (IOException e) {
System.out.println(e);
} finally{
try {
fis.close();
} catch (IOException e) {
System.out.println(e);
} catch (NullPointerException e){
System.out.println(e);
}
}
System.out.println("end");
}
}
// 파일 끝까지 읽기
import java.io.FileInputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
public class FileInputStreamEx {
public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream("input.txt")) {
int i;
while ((i = fis.read()) != -1) {
System.out.println((char) i);
}
System.out.println("end");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.BufferedReader;// 처리 속도 향상. 보조 스트림.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;// 문자열 처리 중심.
// 파일의 내용 끝까지 읽기.
public class FileInputStreamEx {
public static void main(String[] args) {
// 자원자동 반납 리소드 위드 사용코드.
// 한글 처리는?
// 기계-------암호표(ascii, utf-8)--------사람
try (FileInputStream fis = new FileInputStream("input.txt")) {
InputStreamReader reader = new InputStreamReader(fis, "UTF-8");
BufferedReader in=new BufferedReader(reader);
// ascii 코드로 한글이 깨지므로, utf-8언어셋을 지정하여, 깨짐 방지.
int i;
while ((i = in.read()) != -1) {
// fis.read() 는 1바이트의 데이터 리턴.
// -1 리턴시 더이상 읽을 데이터 없음.
System.out.print((char) i);
}
System.out.println("\nend");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
// 파일 복사 예제
public class FileInputStreamEx2 {
public static void main(String[] args) {
long millisecond = 0;
try (FileInputStream fis = new FileInputStream("a.zip");
FileOutputStream fos = new FileOutputStream("copy.zip");
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream bos = new BufferedOutputStream(fos))
{
millisecond = System.currentTimeMillis();
// 시스템의 현재 밀리초 구하기
int i;
while ((i = bis.read()) != -1) {
bos.write(i);
}
millisecond = System.currentTimeMillis() - millisecond;
// 복사하는데 걸린 시간 구하기
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("파일 복사 하는 데 " + millisecond
+ " milliseconds 소요되었습니다.");
}
}

// 직렬화 , 역직렬화 예제
package marchTen;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Person implements Serializable{
private static final long serialVersionUID = -1503252402544036183L;
String name;
// transient String job; // transient 키워드가 붙으면 직렬화에서 예외처리한다는 뜻
String job;
public Person() {}
public Person(String name, String job) {
this.name = name;
this.job = job;
}
public String toString()
{
return name + "," + job;
}
}
public class FileInputStreamEx3 {
public static void main(String[] args) throws ClassNotFoundException {
Person personAhn = new Person("안재용", "대표이사");
Person personKim = new Person("김철수", "상무이사");
try(FileOutputStream fos = new FileOutputStream("serial.out");
ObjectOutputStream oos = new ObjectOutputStream(fos)){
oos.writeObject(personAhn);
oos.writeObject(personKim);
}catch(IOException e) {
e.printStackTrace();
}
try(FileInputStream fis = new FileInputStream("serial.out");
ObjectInputStream ois = new ObjectInputStream(fis)){
Person p1 = (Person)ois.readObject();
Person p2 = (Person)ois.readObject();
System.out.println(p1);
System.out.println(p2);
}catch (IOException e) {
e.printStackTrace();
}
}
}'Java' 카테고리의 다른 글
| Java - day16 (세미프로젝트 - POS구현) (0) | 2022.03.15 |
|---|---|
| Java - day15 (전화번호부 7단계) (0) | 2022.03.10 |
| Java - day14 (추상 클래스 / 인터페이스/StringBulider/HashMap/TreeSet) (0) | 2022.03.08 |
| Java - day13 (자바 연습문제) (0) | 2022.03.07 |
| Java - day12 (전화번호부 HashSet 다른풀이) (0) | 2022.03.06 |
Comments