Algorithm Study
[Java Algorithm] ํ๋ก๊ทธ๋๋จธ์ค Lv.0 _ ํ์ง ๊ตฌ๋ถํ๊ธฐ
microsaurs
2024. 2. 29. 09:42
๐ฟ ๋ฌธ์ ๐ฟ
์์ฐ์ n ์ด ์ ๋ ฅ์ผ๋ก ์ฃผ์ด์ก์ ๋ ๋ง์ฝ n ์ด ์ง์์ด๋ฉด "n is even" ์, ํ์์ด๋ฉด "n is odd" ๋ฅผ ์ถ๋ ฅํ๋ ์ฝ๋๋ฅผ ์์ฑํด๋ณด์ธ์.
[Algorithm]
โก๏ธ 2๋ก ๋๋ด์ ๋, ๋๋จธ์ง์ ์ ๋ฌด๋ฅผ ์ด์ฉํด ํ์ ์ง์๋ฅผ ๊ตฌ๋ถ
* ๋ก์ง ํํ ๋ฐฉ๋ฒ
1. if ๋ฌธ
- System.out.println
- System.out.printf)
2. ์ผํญ์ฐ์ฐ์
[Code]
import java.util.Scanner;
// 1. if๋ฌธ
public class Solution1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
if ( n % 2 == 0 ) {
System.out.println(n + " is even");
} else {
System.out.println(n + " is odd");
}
}
}
// 2. ์ผํญ์ฐ์ฐ์
public class Solution2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.println(n + " is" + (n % 2 == 0 ? "even" : "odd"));
}
}
// 3. System.out.printf ์ฌ์ฉ
public class Solution3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
if ( n % 2 == 0 ) {
System.out.printf("%d is even", n);
} else {
System.out.println("%d is odd", n);
}
}
}
[+ Plus]
โญ๏ธ Java์ ์ถ๋ ฅ๋ฌธ
1. System.out.println()
โก๏ธ ๊ดํธ ์์ ๊ฐ์ ๊ทธ๋๋ก ์ถ๋ ฅ + ๋ง์ง๋ง์ ์ค๋ฐ๊ฟ์ ๋ฃ์ด์ฃผ๋ ๋ฉ์๋
2. System.out.printf()
โก๏ธ ์์๋ฌธ์์ด์ ์ฌ์ฉํ์ฌ ์ถ๋ ฅ
printf("์์๋ฌธ์์ด", value) ํ์์ผ๋ก ์ฌ์ฉ
* ์์๋ฌธ์
- %d : ์ ์ - %f : ์ค์ - %s : ๋ฌธ์์ด - %c : ๋ฌธ์