냥코딩쟝
Published 2023. 3. 10. 20:22
Day19 - 예외 -java spring notes-/JAVA
public class Ex06 {

	public static void main(String[] args) {
		// 
		// Card c1 = new Card();
		// System.out.println(  c1.toString() );  // days19.Card@5aaa6d82  -> SPADE : 1
		// System.out.println(  c1 );
		
		// [ 객체로 부터 Class 객체를 얻어오는 방법 3가지  ]
		// 1) 첫 번째 방법          -    getClass() 메서드 
		/*
		Card c = new Card("HEART", 3);
				
		Class cls = c.getClass();
		System.out.println(  cls.getName() );  // days19.Card     패키지명.클래스명     fullName(풀네임)
		// 풀네임을 적으세요...-> 패키지명.클래스명
		System.out.println(  cls.toString()  );  //  "class days19.Card"
		*/
		
		// 두번째 방법)     모든 클래스명.class    스태틱필드가 제공된다. 
		/*
		Class cls =  Card.class;
		// 얻어온 Class 객체 cls로 부터 인스턴스를 생성할 수 있다. 
		//                                             new Card(); X
		// Object -> Card 다운 캐스팅( 클래스간의 형변환 )
 
		try {
			Card c = (Card) cls.newInstance();
		} catch (InstantiationException | IllegalAccessException e) { 
			e.printStackTrace();
		}
		*/
		   
		// 세번째 방법) 
		// Class 클래스의  스태틱 메서드 - forName() 
		String className = "days19.Card";
		try {
			Class cls = Class.forName(className);   // JDBC 사용~
		} catch (ClassNotFoundException e) { 
			e.printStackTrace();
		}

	} // main

} // class

final class Card{
	String kind; // 카드 종류
	int num;      // 카드 번호
	
	// 디폴트 생성자
	Card(){  
		this( "SPADE", 1 );
	}
	// 생성자
	Card(String kind, int num){
		this.kind = kind;
		this.num = num;
	}
	
	// Object.toString() 재정의 하겠다.   패키지명.클래스명@해쉬코드 16진수값
	@Override
	public String toString() { 
		return String.format("%s : %d", this.kind, this.num);
	}
	
	
}​
package days19;

public class Ex03_04 {
	 

	public static void main(String[] args) {
		

	}

}

// final  키워드 개념 이해
class FinalTest{
	public final int MAX_VALUE = 100;
	public final int MIN_VALUE ; // 명시적 초기화  X
	
	public FinalTest(int min) {
		this.MIN_VALUE = min;  // 생성자 초기화
	}
	
	public void disp( final int m) {
		
	}
}​
package days19;

public class Ex03_04 {
	 

	public static void main(String[] args) {
		

	}

}

// final  키워드 개념 이해
class FinalTest{
	public final int MAX_VALUE = 100;
	public final int MIN_VALUE ; // 명시적 초기화  X
	
	public FinalTest(int min) {
		this.MIN_VALUE = min;  // 생성자 초기화
	}
	
	public void disp( final int m) {
		
	}
}​
public class Ex03_03 {

	public static void main(String[] args) {
	 
			method1(); 

	} // main
	
	private static void method1()   {
		try {
			method2();
		} catch (Exception e) { 
			e.printStackTrace();
		}  // 메서드2를 호출
		System.out.println("> method1() 호출됨..");
	}
	
	// 메서드 선언 + throws 예외1, 예외2...
	private static void method2() throws Exception{
		System.out.println("> method2() 호출됨..");
		
		throw new Exception();  // "checked 예외"
	}

} // class​
public class Ex02 {

	public static void main(String[] args) {
		 // 10:05 수업 시작~ 
		 //[ 예외 발생시키기]
		 //   - 개발자가 고의로 예외를 발생시킬 수 있다.
		 //   왜 ? 국어점 수 입력 받아서 성적 처리 ... 
		 //             111                예외발생 X -> 강제로 예외 발생시켜서 -> 예외 처리.
		 //   - throw 문 사용
		
		  //   형식 : throw  new 발생시킬예외객체();
		  
		
		 //1. throw new RuntimeException();
		//컴파일러가 예외처리를 확인하지 않는  RuntimeException 클래스들을  "unchecked 예외"
		
		// Unhandled exception type Exception
		// 2. throw new Exception();
		//컴파일러가 예외처리를 확인하는 Exception 클래스들을  "checked 예외"
		
	} // main

} // class​
public class Ex01 {

	public static void main(String[] args) {
		// 9:20 제출
		// try~catch문 ( 처리 과정 )
		
		System.out.println("1. 코딩");
		System.out.println("2. 코딩");
		try {			
			System.out.println("3. 코딩");
			System.out.println(   100/0  );
			System.out.println("4. 코딩");
		}catch ( ArithmeticException | NullPointerException e) {  //  멀티 catch문/ 다중 catch문		
			
		}catch (  Exception e  ) {  // ArithmeticException 예외 발생 , 업캐스팅
			System.out.println("5. 코딩");
		} finally {
			// 필수 블럭 X
			// 예외 발생 여부에 상관없이 항상 처리하는 블럭   : finally{}
			System.out.println("finally{}");
			// 이 블럭은 왜 사용합니까? 
			// 예) 파일 OPEN ->  읽기,쓰기  -> 반드시 CLOSE
			//       DB   OPEN ->  CRUD       -> 반드시 CLOSE
		}		
		System.out.println("6. 코딩");
		System.out.println(" 정상적으로 종료!!! ");
		
	} // main

} // class
package days19;

import java.io.IOException;
import java.util.InputMismatchException;
import java.util.Scanner;

/**
 * @author ♈ k§nik
 * @date 2023. 2. 21. - 오전 10:14:33
 * @subject  [ 메서드에 예외 선언하기. ]
 * @content 
 */
public class Ex03_02 {

	public static void main(String[] args)  {
		 
		
		try {
			System.in.read();
		} catch (IOException e1) { 
			e1.printStackTrace();
		}
		
		try {
			int kor =  getScore();   
			System.out.println( kor );
		} catch (ScoreOutOfBoundException  e) { 
			System.out.println(  e.getMessage() );
		}catch (Exception e) { 
			System.out.println(  e.getMessage() );
		}
		
		System.out.println(" end ");
		
		

	}  // main
	
	// 0 ~ 100 점수를 입력받아서 반환하는 메서드  getScore()
	public static int getScore() throws  ScoreOutOfBoundException{
		Scanner scanner = new Scanner(System.in);
		int score;
		
		System.out.print("> 점수 입력 ? ");
		String input = scanner.next();
		String regex = "100|[1-9]?\\d";  // 0~100
		if (  input.matches(regex)  ) {
			score = Integer.parseInt(input);
			return score;
		} else {
			// 강제 예외 발생시키자.
			//               "입력 불일치 예외"
			throw new ScoreOutOfBoundException( 1001,  "> 점수 범위(0~100) 벗어났다. <");
		}
	}

} // class


// 사용자가 정의하는 예외 클래스 
class ScoreOutOfBoundException  extends Exception{

	public ScoreOutOfBoundException(String message) {
		super(message);
		this.ERROR_CODE = 1000;
	}

	// 예외 코드 번호 필드
	private final int ERROR_CODE;
	
	// 11:03 수업 시작~
	public int getERROR_CODE() {
		return this.ERROR_CODE;
	}
	
	public ScoreOutOfBoundException(int errorCode, String message) {
		super(message);
		this.ERROR_CODE = errorCode;
	}
	
}
public class Ex03 {

	public static void main(String[] args)  {
		// 메서드 선언 + 예외 
		// method1 메서드 내에서 발생할 수 있는 예외들을  throws 문을 사용해서 선언한다. 
		// void method1()  throws  E1, E2,E3... {
		//   
	    // }
		
		try {
			System.in.read();
		} catch (IOException e1) { 
			e1.printStackTrace();
		}
		
		try {
			int kor =  getScore();  // 메서드를 호출하는 곳에 예외처리를 해야 된다.. 
			System.out.println( kor );
		} catch (InputMismatchException  e) {
                  // e.printStackTrace();
			System.out.println(  e.getMessage() );
		}catch (Exception e) {
			// TODO: handle exception
		}
		
		System.out.println(" end ");
		
		

	}  // main
	
	// 0 ~ 100 점수를 입력받아서 반환하는 메서드  getScore()
	public static int getScore() throws  InputMismatchException{
		Scanner scanner = new Scanner(System.in);
		int score;
		
		System.out.print("> 점수 입력 ? ");
		String input = scanner.next();
		String regex = "100|[1-9]?\\d";  // 0~100
		if (  input.matches(regex)  ) {
			score = Integer.parseInt(input);
			return score;
		} else {
			// 강제 예외 발생시키자.
			//               "입력 불일치 예외"
			throw new InputMismatchException("> 점수 범위(0~100) 벗어났다. <");
		}
	}

} // class

/*
 * 그러면 방금 예외는 
 * 2가지 catch문중에서 어떤 과정을 거쳐서 "end"가 출력되는건가요??
 */
public class Ex04_02 {

	public static void main(String[] args) {
		String fileName = "C:\\Setup.log";
		
		FileReader fr = null;
		BufferedReader br = null; // 버퍼 기능 + 라인 단위로 처리하는 리더기
		
		// 12:05 수업 시작~ 
		try {
			fr = new FileReader(fileName);
			br = new BufferedReader(fr); // 업캐스팅
			String line ;
			while(     ( line= br.readLine() ) != null    ) {
				System.out.println( line );
			}
			
		} catch (FileNotFoundException e) { 
			e.printStackTrace();
		} catch (IOException e) { 
			e.printStackTrace();
		}finally {
			try {
				fr.close();
				br.close();
			} catch (IOException e) { 
				e.printStackTrace();
			}
		}

	} // main

} // class
public class Ex04_03 {

	public static void main(String[] args) {
		String fileName = "C:\\Setup.log";
		
	   try( 
			   FileReader fr = new FileReader(fileName) ; 
			   BufferedReader br = new BufferedReader(fr);
			   ) {
		    String line ;
		    int lineNumber = 1;
		    while(  ( line = br.readLine()) != null ) {
		    	System.out.printf("%d : %s\n", lineNumber++, line);
		    }
		} catch (Exception e) {
			 e.printStackTrace();
		} 

	} // main

} // class

Java FileReader는 파일을 읽기 위한 스트림을 제공하는 클래스입니다. FileReader는 문자 스트림을 읽어 들이기 때문에, 텍스트 파일을 읽어 들일 때 주로 사용됩니다.

FileReader 객체는 filePath 문자열에 지정된 파일을 엽니다. 그런 다음, read() 메서드를 사용하여 파일에서 문자를 읽어들입니다. read() 메서드는 파일의 끝에 도달할 때까지 한 번에 한 문자씩 반환합니다. 파일을 끝까지 읽으면 -1을 반환

마지막으로, close() 메서드를 사용하여 스트림을 닫아줍니다. FileReader를 사용하여 파일을 열었으면 반드시 닫아주어야한다.

 

public class Ex06 {

   public static void main(String[] args) {
      // 
      // Card c1 = new Card();
      // System.out.println(  c1.toString() );  // days19.Card@5aaa6d82  -> SPADE : 1
      // System.out.println(  c1 );
      
      // [ 객체로 부터 Class 객체를 얻어오는 방법 3가지  ]
      // 1) 첫 번째 방법          -    getClass() 메서드 
      /*
      Card c = new Card("HEART", 3);
            
      Class cls = c.getClass();
      System.out.println(  cls.getName() );  // days19.Card     패키지명.클래스명     fullName(풀네임)
      // 풀네임을 적으세요...-> 패키지명.클래스명
      System.out.println(  cls.toString()  );  //  "class days19.Card"
      */
      
      // 두번째 방법)     모든 클래스명.class    스태틱필드가 제공된다. 
      /*
      Class cls =  Card.class;
      // 얻어온 Class 객체 cls로 부터 인스턴스를 생성할 수 있다. 
      //                                             new Card(); X
      // Object -> Card 다운 캐스팅( 클래스간의 형변환 )
 
      try {
         Card c = (Card) cls.newInstance();
      } catch (InstantiationException | IllegalAccessException e) { 
         e.printStackTrace();
      }
      */
         
      // 세번째 방법) 
      // Class 클래스의  스태틱 메서드 - forName() 
      String className = "days19.Card";
      try {
         Class cls = Class.forName(className);   // JDBC 사용~
      } catch (ClassNotFoundException e) { 
         e.printStackTrace();
      }

   } // main

} // class

final class Card{
   String kind; // 카드 종류
   int num;      // 카드 번호
   
   // 디폴트 생성자
   Card(){  
      this( "SPADE", 1 );
   }
   // 생성자
   Card(String kind, int num){
      this.kind = kind;
      this.num = num;
   }
   
   // Object.toString() 재정의 하겠다.   패키지명.클래스명@해쉬코드 16진수값
   @Override
   public String toString() { 
      return String.format("%s : %d", this.kind, this.num);
   }
   
   
}

getClass() 메서드는 java.lang.Object 클래스에 정의된 메서드로, 해당 객체가 속한 클래스의 Class 객체를 반환합니다.

public class MyClass { // 클래스 멤버들 }

이 클래스의 인스턴스를 생성하고, 이 인스턴스로부터 Class 객체를 얻어오는 코드는 다음과 같습니다.

 

 

// 두번째 방법) 모든 클래스명.class 스태틱필드가 제공된다. /*Class cls = Card.class;// 얻어온 Class 객체 cls로 부터 인스턴스를 생성할 수 있다. // new Card(); X// Object -> Card 다운 캐스팅( 클래스간의 형변환 )try { Card c = (Card) cls.newInstance();} catch (InstantiationException | IllegalAccessException e) { e.printStackTrace();}*/

위 코드에서 obj.getClass() 메서드 호출을 통해MyClass클래스의Class객체를 반환받아clazz변수에 저장하였습니다.
Method[] methods = clazz.getMethods();
for
(Method method : methods) { System.out.println(method.getName()); }
 * @subject    문자열을 다루는 클래스 
 * @content
 *     1) String 클래스                ****
 *     2) StringBuffer 클래스
 *     3) StringBuilder 클래스
 *     4) StringTokenizer 클래스               
 *     
 *     java.util 패키지 안의 클래스 
 *     
 *     날짜/시간 클래스 
 *     
 *     컬렉션 프레임워크
 *  
 */
public class Ex07 {

   public static void main(String[] args) {
      // String 클래스는 "변경 불가능한 클래스"이다. (암기)
      // String name = "홍길동";  // 이 코딩의 의미는 ?    3:02 수업 시작~~
      /*
       *  힙                                                 스택
       *   [홍길동]                                      ["홍길동" 상대주소]
       *  주소                                             name
       *  "홍길동"주소값  
       * 
       * */
      
      /*
      // [질문]  String 클래스  객체 생성하려면   new String();
      String name = new String("홍길동");      
      System.out.println(   name.toString()  );  // "홍길동"
      System.out.println(   name  );  // "홍길동"
      */
      
      // [String 클래스의 메서드 정리]
      String msg = "hello world~";
      System.out.println(  msg.length()  );  //1.  문자열 길이
      System.out.println( msg.charAt( 0) ); // 2. 문자열 에서 위치의 한 문자 얻어오는 메서드
      System.out.println( msg.toUpperCase() ); // 3. 대문자로 변환하는 메서드 
      //                                                                        4.  toLowerCase()
      // 5. 패턴 비교하는 메서드  msg.matches(regex)
      // 6.문자열-> char[] 로 변환하는 메서드 
      char [] arr =  msg.toCharArray();     
      // 7. 문자열 앞 뒤의 공백을 제거하는 메서드  - msg.trim();
      // 8. 문자열 속에서 내가 원하는 beginIndex, endIndex 위치의 문자열을 반환하는 메서드 
      System.out.println( msg.substring(2, 5) );
      // 9. 문자열을 결합(연결)한 문자열을 반환하는 메서드 - concat() 
      // "aaa" + "bbb";
      System.out.println( "aaa".concat("bbb") );  // "aaabbb"
      // 10. 두 문자열이 비교하는 메서드  
      msg.equals("XXX"); // 대소문자 구분해서 비교..
      msg.equalsIgnoreCase("xxx"); // 대소문자 구분 하지 않고 비교 
      
      System.out.println(  "AbC".equals("abc") );  // false
      System.out.println(  "AbC".equalsIgnoreCase("abc") );  // true
      // 11. 
      
      
      
      
      /*
      int [] m = new int[5];
      System.out.println( m.length );
      */

   } // main

} // class

 

 

public class Ex07 {

   public static void main(String[] args) {
      // String 클래스는 "변경 불가능한 클래스"이다. (암기)
      // String name = "홍길동";  // 이 코딩의 의미는 ?    3:02 수업 시작~~
      /*
       *  힙                                                 스택
       *   [홍길동]                                      ["홍길동" 상대주소]
       *  주소                                             name
       *  "홍길동"주소값  
       * 
       * */
      
      /*
      // [질문]  String 클래스  객체 생성하려면   new String();
      String name = new String("홍길동");      
      System.out.println(   name.toString()  );  // "홍길동"
      System.out.println(   name  );  // "홍길동"
      */
      
      // [String 클래스의 메서드 정리]
      String msg = "hello world~";
      System.out.println(  msg.length()  );  //1.  문자열 길이
      System.out.println( msg.charAt( 0) ); // 2. 문자열 에서 위치의 한 문자 얻어오는 메서드
      System.out.println( msg.toUpperCase() ); // 3. 대문자로 변환하는 메서드 
      //                                                                        4.  toLowerCase()
      // 5. 패턴 비교하는 메서드  msg.matches(regex)
      // 6.문자열-> char[] 로 변환하는 메서드 
      char [] arr =  msg.toCharArray();     
      // 7. 문자열 앞 뒤의 공백을 제거하는 메서드  - msg.trim();
      // 8. 문자열 속에서 내가 원하는 beginIndex, endIndex 위치의 문자열을 반환하는 메서드 
      System.out.println( msg.substring(2, 5) );
      // 9. 문자열을 결합(연결)한 문자열을 반환하는 메서드 - concat() 
      // "aaa" + "bbb";
      System.out.println( "aaa".concat("bbb") );  // "aaabbb"
      // 10. 두 문자열이 비교하는 메서드  
      msg.equals("XXX"); // 대소문자 구분해서 비교..
      msg.equalsIgnoreCase("xxx"); // 대소문자 구분 하지 않고 비교 
      
      System.out.println(  "AbC".equals("abc") );  // false
      System.out.println(  "AbC".equalsIgnoreCase("abc") );  // true
      // 11. 
      
      
      
      
      /*
      int [] m = new int[5];
      System.out.println( m.length );
      */

   } // main

} // class

Method[] methods = clazz.getMethods(); for (Method method : methods) { System.out.println(method.getName()); }

 

 

public class Ex07_02 {

   public static void main(String[] args) {
      // 
      String msg = "안녕하세요. Kenik 입니다.";
      // [문제] msg 문자열 속에서 한글은 제거하고 알파벳만을 얻어와서   name 변수에 저장해서 출력하세요.
      //11. 문자열 변경 메서드 : replace()
      // System.out.println( msg.replace("안녕", "XXX") );
      // System.out.println( msg.replace('안', 'X') );
      // msg.replace(  new StringBuffer(), new StringBuilder());
      String name =  msg.replaceAll( "[가-힣]|\\.|\\s" , "");
      System.out.println( name );
      // 4:03 수업 시작~ 
      /*
      String name = "";
      for (int i = 0; i < msg.length(); i++) {
         char one =  msg.charAt(i);
         // if( (  'A' <= one && one <='Z' )  || (  'a' <= one && one <='z' )  )
         if(  Character.isUpperCase(one)    ||  Character.isLowerCase(one)  )
         {
              //  System.out.println(one);
              name += one;
         }
      }
      System.out.println( name );
      */
      
      
      

   }

}
public class Ex07_03 {

   public static void main(String[] args) {
       String team01 = "이태규    ,     김지은 , 설경인,윤재민,   홍성철, 김동현, 박상범 "; 
       // String [] names = team01.split("\\s*,\\s*" ,  3);
       String [] names = team01.split("\\s*,\\s*");
       
       System.out.println( "<ol><li>".concat( String.join("</li><li>", names) ).concat("</li></ol>")  );
       
       
       
       // [람다 와 스트림 ]
       // Arrays.asList(names).forEach( n -> System.out.println(n)   );
       // Arrays.asList(names).forEach( System.out::println   );
       
       /*
       for (String name : names) {
            System.out.printf("[%s]\n", name);
      }
      */
       
       // team01 문자열에서 팀원 String [] 받아서 출력.
       /*
       String [] names = team01.split(",");
       for (String name : names) {
         System.out.printf("[%s]\n", name.trim());
      }
      */
        

   } // main

} // class
public class Ex07_04 {

   public static void main(String[] args) {
      //  dir 문자열 속에 마지막문자열이   '\\' 인지 여부 체크해서 
      String dir = "C:\\temp\\test\\";
      String fileName = "aaa.html";
      
      // dir.length()
      String fullPath ;
      if( dir.charAt( dir.length()-1)  == '\\') {
         fullPath =  dir.concat(fileName);
      }else {
         fullPath =  dir.concat("\\").concat(fileName);
      }     
      System.out.println( fullPath );
      
      //  C:\temp\test\aaa.html
      
      // [질문] 전체경로에서 파일명만 얻어오고 싶어요.               aaa.html
      //         마지막 위치의  \ 뒤의 문자열 얻어오면 파일명.. 
      /*
      for (int i = 0; i < fullPath.length(); i++) {
         System.out.printf("%d - %c\n", i , fullPath.charAt(i));
      }
      */
      
      // int idx =  fullPath.indexOf("\\");
      int idx =  fullPath.lastIndexOf("\\");
      System.out.println(   fullPath.substring(  idx + 1 )  );
      
      // [질문] 전체경로에서 확장자만 얻어오고 싶어요 ..             .html
      //            . 위치 찾아서 그 뒤의 확장자를 얻어오겠다.
      idx = fullPath.lastIndexOf(".");
      System.out.println(   fullPath.substring(idx+1)  );
      
      // 5:09 수업 시작~ 
      
 
      
      

   } // main

}// class
public class Ex07_05 {

   public static void main(String[] args) {
      String url = "www.naver.com";     
      // url 반드시  http://       문자열로  시작을 해야 된다라고..
      
      String prefix = "http://";  // 접두사
      System.out.println( url.startsWith(prefix) );  // boolean
      
      
      String dir = "c:\\temp\\test";
      String suffix = "\\";  // 접미사 
      System.out.println( dir.endsWith(suffix)  );  // boolean
      
      String b = "abc";  // 65
      String a = "aCc";   // 97
      
      System.out.println(  a.compareTo(b) ); //   0   양수, 음수    -32
      
      // 두 문자열 같냐 ? 
      System.out.println(  a.equals(b) );  // false
      System.out.println(  a.equalsIgnoreCase(b) );  // truc
      

      // "aaa" + "bbb" + "ccc"
      // "aaa".concat("bbb").concat("ccc")
      
      // 1조원 중에 김지은 있냐? 
       String team01 = "이태규    ,     김지은 , 설경인,윤재민,   홍성철, 김동현, 박상범 "; 
       System.out.println( team01.contains("김지은") );  // true/false
       
      // -1  indexOf()/ lastIndexOf()
       
       // 문자열 -> byte[] 변환해서 반환하는 메서드  :  getBytes();
       byte [] m =  "안녕하세요. 홍길동입니다.".getBytes();
       System.out.println(  Arrays.toString( m ));
       // byte[] -> 문자열 변환
       System.out.println( new String( m ) );
       // 
        
       
       
      
   }

}

 

profile

냥코딩쟝

@yejang

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