728x90

 기본 환경: IDE: Eclipse, Language: Java

 

 

발생 Exception

Java에서 다음 Source Code를 실행할 경우,

import java.util.*;
import java.text.*;

public class Today {

	public static void main(String[] args) {
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmss"); // java.text
		Date birth = sdf2.parse("20230213184030"); // java.util, String -> Date 형변환
		System.out.println("Birth: " + sdf2.format(birth));
		
	}
	
}

⭐ java.lang.Error: Unresolved compilation problem:

→ Unhandled exception type ParseException 발생

 

 

Exception 원인

문자열을 기반으로 객체를 만드는데 파싱*에서 에러가 발생할 경우, ParseException이 발생

*파싱(Parsing): 구문 분석, 주어진 정보를 내가 원하는 형태로 가공하는 것

Source Code상의 문제는 없으나, Compile Error가 발생할 수 있기때문에 Exception에 대한 처리 필요

 

 

해결 방법

1. Add throws declaration

import java.util.*;
import java.text.*;

public class Today {

	public static void main(String[] args) throws ParseException {
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmss"); // java.text
		Date birth = sdf2.parse("20230213184030"); // java.util, String -> Date 형변환
		System.out.println("Birth: " + sdf2.format(birth));
		
	}
	
}

 

2. Surround with try/catch

import java.util.*;
import java.text.*;

public class Today {

	public static void main(String[] args) {
		Date date = new Date();
		System.out.println("오늘 날짜: " + date);
		
		SimpleDateFormat sdf = new SimpleDateFormat("y년 MM월 dd일 E요일 HH:mm:ss");
		System.out.println("오늘 날짜: " + sdf.format(date));
		
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmss"); // java.text

		Date birth=null;
		try {
			birth = sdf2.parse("20230213184030");
		} catch (ParseException e) {
			e.printStackTrace();
		} // java.util, String -> Date 형변환
		System.out.println("Birth: " + sdf2.format(birth));
	}
	
}

 

 

 

참고 자료

📑 Live Study 9주차 - 예외 처리

📑 [JAVA] Parsing이란 무엇인가?

 

728x90
728x90

기본 환경: IDE: Eclipse, Language: Java

 

발생 Warning

Java에서 다음 Source Code를 실행할 경우,

package basic;

import java.util.*;

public class AvoidLeakage {

	public static void main(String[] args) {
		Scanner scan2 = new Scanner(System.in);
		System.out.println("Enter the String2: ");
		String s2 = scan2.next();
	}

}

Resource leak: 'scan2' is never closed

→ Warning  발생

 

 

Warning 원인

입력 시, 키보드 외에도 파일 등을 통해 입력을 받는 경우도 있음
(파일작업 순서: 파일 열기 → 파일 사용 → 파일 닫기)
⭐ 파일을 열어놓고 닫지 않을 경우, 파일이 손상될 수가 있으므로 파일 작업은 열고 닫는 과정을 명시적으로 입력해야 함
 스캐너 생성 시 파라미터로 값을 넘기게 되는데(new Scanner(System.in), in: 키보드 입력), 키보드 입력의 경우 close()를 해주지 않아도 상관 없지만 리소스를 사용하는 경우에는 되도록 close()해주는 습관을 들이는 것이 좋음

 

 

해결 방법

Scanner class type variable scan에 대한 close() 추가

package basic;

import java.util.*;

public class AvoidLeakage {

	public static void main(String[] args) {
		Scanner scan2 = new Scanner(System.in);
		System.out.println("Enter the String2: ");
		String s2 = scan2.next();
		
		scan2.close();
	}
}

⚠️ System.in으로 키보드를 통한 입력받을 대상이 남아있음에도 불구하고 close()할 경우 ,

package basic;

import java.util.*;

public class AvoidLeakage {

	public static void main(String[] args) {
		Scanner scan2 = new Scanner(System.in);
		System.out.println("Enter the String2: ");
		String s2 = scan2.next();
		
		scan2.close();
		
		String s3 = scan2.next();
	}
}

java.lang.IllegalStateException: Scanner closed 발생 → ⭐ 입력을 모두 마친 후, scan.close() 작성

 

 

 

➕ Scanner class 객체 생성을 main() 내부가 아닌 class에 직접 생성할 경우, Resource Leakage 발생 X

package basic;

import java.util.*;

class AvoidLeakage2{
	Scanner scan = new Scanner(System.in);

	public void printS() {
		System.out.println("Enter the String: ");
		String s = scan.next();
	}
}

 

참고 자료

📑 자바 sc.close();

 

 

728x90

'Java > Java with Error' 카테고리의 다른 글

[해결 방법] java.lang.Error  (0) 2023.02.16
[해결 방법] java.lang.Error  (0) 2023.02.13
[해결 방법] java.lang.Error  (0) 2023.02.12
[해결 방법] java.lang.Error  (0) 2023.02.11
[해결 방법] java.lang.NullPointerException  (0) 2023.02.11
728x90

 기본 환경: IDE: Eclipse, Language: Java

 

발생 Error

Java에서 다음 Source Code를 실행할 경우,

else {
	int index = input.indexOf(repOld);
	int count=0;

	while(index > -1) {
		count++;
		index = input.indexOf(repOld, index + repNew.length());
	} // while: find String
			
	if(index!=-1) {
		String inputNew = input.replace(repOld, repNew);
	} System.out.println(inputNew);
}

inputNew cannot be resolved to a variable

→ java.lang.Error: Unresolved compilation problem 발생

 

 

Error 원인

String inputNew를 if-else 구문 내 선언하여 지역변수화 됨

else 구문 밖 println문에서는 해당 변수를 사용할 수 없음

 

 

해결 방법

else 구문 밖에서 String inputNew 선언 후, else 구문 안에서 값 계산

else {
	int index = input.indexOf(repOld);
	int count=0;
        String inputNew=""; // Initialization

	while(index > -1) {
		count++;
		index = input.indexOf(repOld, index + repNew.length());
	} // while: find String
			
	if(input.indexOf(repOld)!=-1) {
		inputNew = input.replace(repOld, repNew);
	} System.out.println(inputNew);
}

 

 

 

728x90
728x90

 기본 환경: IDE: Eclipse, Language: Java

 

발생 Error

Java에서 다음 Source Code를 실행할 경우,

public static void main(String[] args) {
	int a; // 4byte(32bit) memory instance 생성
	System.out.println("Local Variable a = " + a);
}

The local variable a may not have been initialized

→ java.lang.Error: Unresolved compilation problem 발생

 

 

Error 원인

int a 선언 후, 초기값을 지정하지 않음

: method 내부의 지역 변수(Local value)의 경우, garbage value가 초기에 저장되어있으므로 초기값 설정이 필요

 

 

해결 방법

int a 선언 후, 초기값 지정

public static void main(String[] args) {
	int a=0; // 4byte(32bit) memory instance 생성
	System.out.println("Local Variable a = " + a);
}

 

 

 

➕ 전역 변수의 초기값 설정

public class Variable02 {
	int a; // Field, Global Variable: Class 내부에서 사용 가능
	// Field는 초기화가 되어있으므로 변수값 지정없이 사용 가능
	double b;
	static int c;
	// static variable의 경우, memory 할당이 필요없이 자동으로 메모리에 공간이 부여되어있음(메모리 할당 선언 필요X)

	public static void main(String[] args) {
		Variable02 v = new Variable02(); // Variable Class memory 생성
		// v: Variable02의 address 보유(Class_name@16진수_참조주소값)
		System.out.println("Variable02: " + v);
		// Variable02: basic.Variable02@515f550a (pkg.Class@ref_address)
		
		System.out.println("Field a = " + v.a); // field 출력: Default 0
		// Variable02의 주소값을 가진 v에서 해당 클래스의 필드값 a를 출력
		System.out.println("Field b = " + v.b); // field 출력: Default 0.0
		System.out.println("Field c = " + c); // field 출력: Default 0
		// Variable02.c와 동일
		// v.c 사용 필요 X
	}
}

class에서 직접 선언되는 전역변수(Global value)의 경우에는 초기값 설정이 되어있으므로 초기값 설정 불요

 

public class Default_value {
	boolean a;
	char b;
	byte c;
	short d;
	int e;
	long f;
	float g;
	double h;
	
	public static void main(String[] args) {
		Default_value dv = new Default_value();
		System.out.println("Default boolean: " + dv.a); // false
		System.out.println("Default char: " + dv.b); // '\0'
		System.out.println("Default byte: " + dv.c); // 0
		System.out.println("Default short: " + dv.d); // 0
		System.out.println("Default int: " + dv.e); // 0
		System.out.println("Default long: " + dv.f); // 0
		System.out.println("Default float: " + dv.g); // 0.0
		System.out.println("Default double: " + dv.h); // 0.0
	}
	
}

 

 

728x90
728x90

 기본 환경: IDE: Eclipse, Language: Java

 

발생 Exception

Java에서 다음 Source Code를 실행할 경우,

public class Exam {
	private char[] ox=null;

	public void compare() {
		for(int i=0; i<JUNG.length(); i++) {
			if(dap.charAt(i)==JUNG.charAt(i)) {
				ox[i] = (char)'O';
			} else {ox[i] = (char)'X';}
		} // for
	} // compare
}

Exception in thread "main" java.lang.NullPointerException: Cannot store to char array because "this.ox" is null

→ NullPointerException 발생

 

 

Exception 원인

char[]를 선언 후, 배열의 크기를 지정해주는 초기화 작업을 진행하지 않음

 

 

해결 방법

public class Exam {
	private char[] ox=null;

	public void compare() {
    ox = new char[JUNG.length()];
    
		for(int i=0; i<JUNG.length(); i++) {
			if(dap.charAt(i)==JUNG.charAt(i)) {
				ox[i] = (char)'O';
			} else {ox[i] = (char)'X';}
		} // for
	} // compare
}

/*
Result
O	X	X	O	O
*/

ox = new char[JUNG.length()];

: ox 배열에 대해 크기 지정

 

 

 

참고 자료

📑 why can't I assign null to a particular index of Char Array?

📑 Primitive Types

📑 charGPT

 

728x90