주어진 문자열을 정수로 변경하는 예제
private int parseIntOrThrow(@NotNull String str) {
try {
return Integer.parseInt(str);
} catch (NumberFormatException e) {
throw new IllegalArgumentException(String.format("주어진 $s는 숫자가 아닙니다", str));
}
}
fun parseIntOrThrow(str: String): Int {
try {
return str.toInt()
} catch (e: NumberFormatException) {
throw IllegalArgumentException("주어진 ${str}은 숫자가 아닙니다.")
}
}
주어진 문자열을 정수로 변경하는 예제, 실패하면 null을 반환
private Integer parseIntOrThrowV2(String str) {
try {
return Integer.parseInt(str);
} catch (NumberFormatException e) {
return null;
}
}
fun parseIntOrThrowV2(str: String): Int? {
return try {
str.toInt()
} catch (e: NumberFormatException) {
null
}
}
프로젝트 내 파일의 내용물을 읽어오는 예제
public void readFile() throws IOException {
File currentFile = new File(".");
File file = new File(currentFile.getAbsoluteFile() + "/a.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
System.out.println(reader.readLine());
reader.close();
}
fun readFile() {
val currentFile = File(".")
val file = File(currentFile.absolutePath + "/a.txt")
val reader = BufferedReader(FileReader(file))
println(reader.readLine())
reader.close()
}