728x90

array 초기화 3가지

 

1) 인덱스 이용

 

2) 중괄호{ } 이용

 

3) for문 이용

 

import java.util.Scanner;

public class practice_everyday13 {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		
		int[] arr0; 		// 배열선언
		arr0 = new int[5];	// 배열할당
		
		// array 초기화 3가지
		// 1)인덱스
		int[] arr = new int[3];
		arr[0] = 1;
		arr[1] = 2;
		arr[2] = 3;
		
		for(int i=0; i<arr.length;i++) { // 출력용 for문
			System.out.print(+arr[i]);
		}
		
		// 2)중괄호 {}
		int[] arr2 = {1,2,3};
		
		for(int i=0; i<arr2.length;i++) { // 출력용 for문
			System.out.print(+arr2[i]);
		}
		
		// 3)for문 초기화
		int[] arr3 = new int[4];
		for(int i = 0; i<arr3.length; i++) {
			arr3[i] = i*10+1; 			// for문 초기화
			System.out.println(arr3[i]);
		}
		
	}
	
		
}

 

728x90
반응형
728x90

 

 

 

 

 

 

import java.util.Scanner;

public class practice_everyday13 {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		// 삼항연산자 (2중) + do while문
		int num1;
		int num2;
		do { 
			System.out.print("수1 입력 : ");
			num = sc.nextInt();
			System.out.print("수2 입력 : ");
			num2 = sc.nextInt();
			System.out.println(num1 == num2 ? "같아 멈춰":(num1>num2 ? "1이 커":"2가 커"));
			
		}while(num1 !=num2);
			
		// for문 초기화 생략
		int num3 = 5;
		int i = 0;
		for(; i < num3; i+=2) { // 초기화 생략 : int i +=0;
			System.out.println(i);
		}	
    }
}
728x90
반응형
728x90

아래 이미지는 1번 파일을 0번 파일이 상속했다

자식 클래스 부모 클래스의 이름을 눌러보면 부모클래스와 연결되어있는 코드들의 색깔이 진해진다

이 코드들은 중복이기에 삭제하여도 부모와 자식 클래스의 정보가 연동된다

 

삭제 전

삭제 후

0번 parent 

1번 child1

2번 child2

상속관계가 0 -> 1 -> 2

1번이 0번을 상속하고 2번이 1번을 상속한 것

 

1번 child1에서 parent에 받았던 a,b부분들을 주석 처리해서 2번 child2에서 보면 정보가 그대로인 걸 알 수 있다

 

public class practice_everyday04 {
	public static void main(String[] args) {
		
		// run
		practice_everyday04_0 pe1 = new practice_everyday04_0();
		pe1.println();
		
		practice_everyday04_1 pe2 = new practice_everyday04_1();
		pe2.println();
		
		practice_everyday04_2 pe3 = new practice_everyday04_2();
		pe3.println();
		
	}	
}
public class practice_everyday04_0 {
	
	// Parent
	private int a;
	private int b;
	
	public practice_everyday04_0() {}
	public practice_everyday04_0(int a, int b) {
		this.a = a;
		this.b = b;
	}
	//getter & setter
	public int getA() {
		return a;
	}
	public void setA(int a) {
		this.a = a;	
	}
	public int getB() {
		return b;
	}
	public void setB(int b) {
		this.b = b;
	}
	
	
	public void println() {
		System.out.println("parent");
	}
	
}

 



public class practice_everyday04_1 extends practice_everyday04_0 {
		
	// child1
//	private int a;
//	private int b;
	private int c;
	
	public practice_everyday04_1() {}
	public practice_everyday04_1(int a, int b, int c) {
//		this.a = a;
//		this.b = b;
		this.c = c;
	}
	
	// getter & setter
	// setter : 데이터를 변수에 저장하는 메소드
	// getter : 저장된 데이터를 불러오는 메소드
//		public int getA() {
//			return a;
//		}
//		public void setA(int a) {
//			this.a = a;	
//		}
//		public int getB() {
//			return b;
//		}
//		public void setB(int b) {
//			this.b = b;
//		}
		public int getC() {
			return c;
		}
		public void setC(int c) {
			this.c = c;
		}
		
	@Override	
	public void println() {
		System.out.println("child1");
	}
	
}

 

// 상속 & overriding
public class practice_everyday04_2 extends practice_everyday04_1{
	
	// child2
	private int a;
	private int b;
	private int c;
	private int d;
	
	public practice_everyday04_2() {}
	public practice_everyday04_2(int a, int b, int c, int d) {
		this.a = a;
		this.b = b;
		this.c = c;
		this.d = d;
	}
	
	// getter & setter
		public int getA() {
			return a;
		}
		public void setA(int a) {
			this.a = a;	
		}
		public int getB() {
			return b;
		}
		public void setB(int b) {
			this.b = b;
		}
		public int getC() {
			return c;
		}
		public void setC(int c) {
			this.c = c;
		}
		public int getD() {
			return d;
		}
		public void setD(int d) {
			this.d = d;
		}
	@Override
	public void println() {
		System.out.println("child2");
	}
		

	
	
		
}

 

728x90
반응형
728x90

 

try with resource

자동으로 close() 해주는 구문

close()를 위해 finally 구문을 사용할 필요도 없어진다 

 

 

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class practice_everyday10 {
		
		// 1.바이트 기반+보조 : 입력
	public void Stream_outputByte() {
		// 목적 : 파일에 바이트기반으로 데이터를 빠르게 쓰고 싶다
		try (BufferedOutputStream bos = new BufferedOutputStream(
				new FileOutputStream("D:\\test\\test.txt"))){
			
			bos.write(65);
			byte[] arr = {66,67,68,69};
			bos.write(arr);
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void Stream_inputByte() {
		// 목적 :파일에 있는 데이터를 바이트 기반으로 빠르게 읽어오고 싶다
		try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\\test\\test.txt"))) {
			
			int val;
			while((val=bis.read()) != -1) {
				System.out.println(val);
			}	
		} catch (IOException e) { //IOException이 FileInputStream의 부모이기에 따로 예외처리하지않아도 같이 처리
			e.printStackTrace();
		}
		
	}	
}

 

 

728x90
반응형
728x90

 

기반 스트림 + 보조 스트림

성능향상

 

 

 

public class practice_everyday09_Run {
	public static void main(String[] args) {
		practice_everyday09 pe9 = new practice_everyday09();
		
		pe9.Stream_outputByte();
		pe9.Stream_inputByte();

	}	
}

 

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class practice_everyday09 {
		
		// 1.바이트 기반+보조
		// 2.문자 기반+보조
		
		
		// 1.바이트 기반+보조 : 입력
	public void Stream_outputByte() {
		// 목적 : 파일에 바이트기반으로 데이터를 빠르게 쓰고 싶다
		FileOutputStream fos;
		BufferedOutputStream bos = null;
		try {
			fos = new FileOutputStream("D:\\test\\test.txt");
			bos = new BufferedOutputStream(fos);
			
			bos.write(65);
			byte[] arr = {66,67,68,69};
			bos.write(arr);
			
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public void Stream_inputByte() {
		// 목적 :파일에 있는 데이터를 바이트 기반으로 빠르게 읽어오고 싶다
		FileInputStream fis;
		try {
			fis = new FileInputStream("D:\\test\\test.txt");
			BufferedInputStream bis = new BufferedInputStream(fis);
			
			int val;
			while((val=bis.read()) != -1) {
				System.out.println(val);
			}	
		} catch (IOException e) { // IOE
			e.printStackTrace();
		}
		
		

	// 2.문자 기반+보조

		
		
	}	
}
728x90
반응형
728x90

 

 

 

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class practice_everyday07 {
	public static void main(String[] args) throws IOException {
		
		// 문자 기반 스트림
		// FileReader
		// FileWriter
		
		FileWriter fw = new FileWriter("D:\\file\\file2\\first.txt");
		fw.write("initiate\n");
		fw.append("2\n");
		char[] cArray = {'c','h','e','e','r'};
		char[] sArray = {'u','p'};
		fw.write(cArray);
		fw.write(sArray);
		fw.close();
		
		FileReader fr = new FileReader("D:\\file\\file2\\first.txt");
		int i;
		while((i=fr.read()) != -1) {
			System.out.print((char)i);
		}
		fr.close();
		
	}	
}
728x90
반응형
728x90

 

File class의 많이 쓰는 메소드

f1.mkdir() : 해당 디렉토리 생성. 생성하려는 폴더 직전까지의 경로가 다 생성되어있어야 생성하려는 폴더 생성가능

경로 생성이 제대로 안되어있으면 생성이 안될 뿐 에러발생은 안난다

f1.mkdirs() : 해당 디렉토리 생성. 생성하려는 폴더 직전까지 없는 경로도 같이 생성

f1.creatNewFile()

f1.delete

f1.exists() : 존재하냐?

f1.isFile() : 파일이냐?

f1.getName() : 파일명 get

f1.getAbsolutePath() : 절대경로 반환

f1.getPath() : 상대경로 반환

f1.length() : 파일용량

f1.getParent() : 상위 폴더 경로 반환

 

 

 

 

import java.io.File;
import java.io.IOException;

public class practice_everyday06 {
	
	public static void main(String[] args) {
		
	File f = new File("D:\\file\\file1.txt");		// 경로지정 방법1
//	File f = new File("D:/file.txt");  		// 경로지정 방법2
//	File f = new File("D:/file.txt",true);  // ,true : 파일 내용 추가
		
		f.mkdir();  // 해당 디렉토리 생성. 생성하려는 폴더 직전까지의 경로가 다 생성되어있어야 생성하려는 폴더 생성가능
					// 경로 생성이 제대로 안되어있으면 생성이 안될 뿐 에러발생은 안난다
		f.mkdirs(); // 해당 디렉토리 생성. 생성하려는 폴더 직전까지 없는 경로도 같이 생성
		
		f.exists(); // true
		f.isFile(); // false
		System.out.println(f.exists());
		System.out.println(f.isFile());
		
	File ff = new File("D:\\file\\file2");
		System.out.println(ff.exists()); // false
		System.out.println(ff.isFile()); // false
		
		ff.mkdirs();	// 파일 생성 
		System.out.println(ff.exists()); // true
		System.out.println(ff.isFile()); // false
		System.out.println();
		
		System.out.println(ff.getName()); // file2
		System.out.println(ff.getAbsolutePath());  // D:\file\file2
		System.out.println(ff.getPath()); //상대경로 // D:\file\file2
		System.out.println(ff.length()); 		  // 0
		System.out.println(ff.getParent()); 	  // D:\file
		
		
		
		
		
		
		try {
			f.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		} 
		
		
		
	}	
}

 

 

728x90
반응형
728x90

 

한바퀴 도는 메소드 먼저 하나 만들었다

한바퀴 돌기 좋은 코드 로직인 것 같다

이제 예외(Exception)를 강제 발생시켜 예외처리 연습을 해보려한다

 

IOException 임포트 후에 예외 강제 발생 코드인 throw를 넣고 런시키니 뜬 에러메세지

Unhandled exception type IOException 

Unreachable code

 

Unhandled exception type IOException는  IOException을 예외처리 못했다는 의미이고

Unreachable code는 예외가 발생되면 발생된 곳 이후 코드들은 전부 작동하지 않기에 닿지않는 코드라고 에러가 뜨는 것이다. println 결력도 call_3메소드는 출력되지 않고 2까지만 되고 있다

이제 발생한 예외를 try catch문을 써서 직접 처리 해본다

 

 

코드 call_1 off까지 끝까지 잘 작동한다.

아래 빨간줄은 에러처럼 보이지만 catch문 안에 e.printStackTrace();에서 .printStackTrace()이 에러 정보를 보여주기 때문에 나오는 것이다. 에러메세지가 아니니 걱정하지 않아도 된다.

 

 

 .printStackTrace()지워보면 빨간줄이 전부 사라진다.

 

기능클래스의 메소드 call_3에서 직접 예외처리 했지만,

런파일에서 pe4.call_3를 try문 안에 넣고 해도 된다

728x90
반응형
728x90

 

String 안에 쓸 수 있는 많이 쓰는 메소드

1)charAt ()

2)concat()

3)equals()

4)substring()

5)replace()

 

 

public class practice_everyday01 {
	public static void main(String[] args) {	
		
		// String methods
		String str = "힘을 내라";
		
		// 1)charAt ()
		// charAt(int index):char
		char cheer = str.charAt(0);
		System.out.println(cheer); // 힘
		
		// 2) concat()
		// concat(String str):String
		// 원래 문자열 끝에 매개변수로 들어온 값을 이어붙인 문자열 반환
		String cstr = str.concat(" save it");
		System.out.println(cstr);
		
		
		// 3) equals()
		// equals(Object anObject):boolean
		System.out.println(str.equals(cstr));
		
		// 4)substring()
		// substring(int beginIndex):String
		// 해당 인덱스 넘버부터 문자열 시작. 
		// substring(int beginIndex, int endIndex):String
		// A to B 사이의 문자열 일부 반환
		
		System.out.println(str.substring(2));
		System.out.println(str.substring(0,3));
		
		
		// 5)5)replace()
		// replace(char oldChar, char newChar):String
		
		System.out.println(str.replace('힘','손'));
	}	
}
728x90
반응형
728x90

 

StringBuffer 안에 쓸 수 있는 많이 쓰는 메소드

append(),  insert(), delete(), reverse()

 

 

public class practice_everyday01 {
	public static void main(String[] args) {	
		
		// StringBuffer
		
		// 1) append()
		// 받아온 값을 뒤에 추가로 이어주는 메소드
		StringBuffer sb1 = new StringBuffer();
		sb1.append("a"); // str
		sb1.append('1'); // char
		sb1.append(2);   // int
		System.out.println(sb1); // 문자열 취급 더하기 a+1+2=a12
 		// a12
		
		// 2) insert()
		// 특정 인덱스번호에 문자열 삽입기능
		sb1.insert(1, "b");  	// 인덱스1 위치에 넣으면 원래 1에 있던 문자는 뒤로 밀려난다 
		sb1.insert(2, 'c');  	// 인덱스1 위치에 넣으면 원래 1에 있던 문자는 뒤로 밀려난다 
		System.out.println(sb1);// ""나 ''나 둘 다 작동
		//abc12
		
		// 3)delete 
		// delete(start, end-1)
		sb1.delete(3, 5);  		// end 숫자의 -1까지 삭제한다 1부터5라면 1부터4까지만 지운다
		System.out.println(sb1);
		// abc
		
		// 4)reverse
		sb1.reverse();  // 문자열을 거꾸로 돌려서 출력
		System.out.println(sb1);
		// cba
	}	
}
728x90
반응형

+ Recent posts