fun getGrade(score: Int):String {
return if (score >= 90) {
"A"
} else if (score >= 80) {
"B"
} else if (score >= 70) {
"C"
} else {
"D"
}
}
if (score in 0..100) {
when(값) {
조건부 -> 어떠한 구문
조건부 -> 어떠한 구문
else -> 어떠한 구문
}
fun getGradeWithSwitch(score: Int): String {
return when (score / 10) {
9 -> "A"
8 -> "B"
7 -> "C"
else -> "D"
}
}
fun getGradeWithSwitch(score: Int): String {
return when (score) {
in 90..99 -> "A"
in 80..89 -> "B"
in 70..79 -> "C"
else -> "D"
}
}
fun judgeNumber(number: Int) {
when (number) {
1, 0, -1 -> println("1, 0, -1입니다.")
else -> println("1, 0, -1이 아닙니다.")
}
}
fun judgeNumber2(number: Int) {
when {
number == 0 -> println("주어진 숫자는 0입니다.")
number % 2 -> println("주어진 숫자는 짝수입니다")
else -> println("주어지는 숫자는 홀수입니다")
}
}
val numbers = listOf(1L, 2L, 3L)
for (number in numbers) {
println(number)
}
for (i in 1..3) {
println(3)
}
for (i in 3 downTo 1) {
println(i)
}
for (i in 1..5 step 2) {
println(i)
}
var i = 1
while (i <= 3) {
println(i)
i++
}
fun parseIntOrThrow(str: String): Int {
try {
return str.toInt()
} catch (e: NumberFormatException) {
throw IllegalArgumentException("주어진 ${str}는 숫자가 아닙니다")
}
}
fun parseIntOrThrowV2(str: String): Int? {
return try {
str.toInt()
} catch (e: NumberFormatException) {
null
}
}
public void readFile(String path) throw IOException {
try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
System.out.println(reader.readLine());
}
}
fun readFile(path: String) {
BufferedReader(FileReader(path)).use{ reader ->
println(reader.readLine())
}
}
fun max(a: Int, b: Int) = if (a > b) a else b
fun repeat(
str: String,
num: Int = 3,
useNewLine: Boolean = true
) {
for (i in 1..num) {
if (useNewLine) {
println(str)
else {
print(str)
}
}
}
repeat("Hello World", useNewLine = false)
public static void printAll(String... strings) {
for (String str : strings) {
System.out.println(str);
}
}
String[] array = new String[]{"A", "B", "C};
printAll(array);
printAll("A, "B, "C);
fun printAll(vararg strings: String) {
for (str in strings) {
println(str)
}
}
printAll("A", "B", "C)
val array = arrayOf("A", "B", "C")
printAll(*array)
참고