Q1. operator 값이 +, -, *, /인 경우에 사칙 연산을 수행하는 프로그램을 if-else문과 swtich-case문을 사용해 작성해 보세요.
public class C4_Q1 {
public static void main(String[] args) {
int num1 = 10;
int num2 = 2;
int result = 0;
char operator = '+';
// if
if(operator == '+') {result = num1 + num2;}
else if(operator == '-') {result = num1 - num2;}
else if(operator == '*') {result = num1 * num2;}
else if(operator == '/') {result = num1 / num2;}
else System.out.println("잘못된 입력");
//switch
switch(operator) {
case '+': result = num1 + num2; break;
case '-': result = num1 - num2; break;
case '*': result = num1 * num2; break;
case '/': result = num1 / num2; break;
default: System.out.println("잘못된 입력"); }
System.out.println("result: " + result);
}
}
Q2. 구구단을 짝수 단만 출력하도록 프로그램을 만들어 보세요.
public class C4_Q2 {
public static void main(String[] args) {
for(int i=2; i<10; i++) {
if(i%2 != 0) continue;
for(int j=1; j<10; j++) {
System.out.print(i + "x" + j + "=" + i*j +'\t');
} System.out.println();
}
}
}
Q3. 구구단을 단보다 곱하는 수가 작거나 같은 경우까지만 출력하는 프로그램을 만들어보세요.
public class C4_Q3 {
public static void main(String[] args) {
for(int i=2; i<10; i++) {
for(int j=1; j<10; j++) {
if (i<=j) break;
System.out.print(i + "x" + j + "=" + i*j +'\t');
} System.out.println();
}
}
}
Q4. 반복문을 사용하여 다음 모양을 출력하는 프로그램을 만들어보세요.
public class C4_Q4 {
public static void main(String[] args) {
for(int i=0; i<4; i++) {
for(int j=1; j<4-i; j++) {System.out.print(" ");}
for(int j=0; j<i*2+1; j++) {System.out.print("*");}
System.out.println();
}
}
}
Q5.
public class C4_Q4 {
public static void main(String[] args) {
for(int i=0; i<4; i++) {
for(int j=1; j<4-i; j++) {System.out.print(" ");}
for(int j=0; j<i*2+1; j++) {System.out.print("*");}
System.out.println();
}
for (int i=3; i>0; i--) {
for (int j=4-i; j>0; j--) {System.out.print(" ");}
for (int j=i*2-1; j>0; j--) {System.out.print("*");}
System.out.println();
}
}
}
'JAVA > Do it! 자바 프로그래밍 입문' 카테고리의 다른 글
[Do it 자바 프로그래밍 입문] 05 클래스와 객체 1 연습문제 (0) | 2023.03.24 |
---|---|
[Do it 자바 프로그래밍 입문] 05 클래스와 객체 1 (0) | 2023.03.24 |
[Do it 자바 프로그래밍 입문] 04 제어 흐름 이해하기 (0) | 2023.03.23 |
[Do it 자바 프로그래밍 입문] 03 자바의 여러 가지 연산자 연습문제 (0) | 2023.03.23 |
[Do it 자바 프로그래밍 입문] 03 자바의 여러 가지 연산자 (0) | 2023.03.23 |