1. 계산기 프로그램을 작성하되 각 연산자의 연산은 메서드를 통해서 작성
- 코드
import java.util.Scanner;
public class Test01 {
public static int plus(int num, int num2) { // 더하기 메서드
int tot = num + num2;
return tot;
}
public static int minus(int num, int num2) { // 빼기 메서드
int tot = num - num2;
return tot;
}
public static int multiply(int num, int num2) { // 곱하기 메서드
int tot = num * num2;
return tot;
}
public static int division(int num, int num2) { // / 연산 메서드
int tot = num / num2;
return tot;
}
public static int division2(int num, int num2) { // % 연산 메서드
int tot = num % num2;
return tot;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("su1 : "); // 첫 번째 수를 입력받아 저장
int first = sc.nextInt();
System.out.print("yon<+, -, *, /, %> : ");
String yon = sc.nextLine(); // 연산자를 입력받아 저장
System.out.print("su2 : ");
int second = sc.nextInt(); // 두 번째 수를 입력받아 저장
if(yon.equals("+")) // 연산자가 +일 경우 더하기 메서드 실행
System.out.println(first+" "+yon+" "+second+" = "+plus(first, second));
else if(yon.equals("-")) // 연산자가 -일 경우
System.out.println(first+" "+yon+" "+second+" = "+minus(first, second));
else if(yon.equals("*")) // 연산자가 *일 경우
System.out.println(first+" "+yon+" "+second+" = "+multiply(first, second));
else if(yon.equals("/")) // 연산자가 /일 경우
System.out.println(first+" "+yon+" "+second+" = "+division(first, second));
else if(yon.equals("%")) // 연산자가 %일 경우
System.out.println(first+" "+yon+" "+second+" = "+division2(first, second));
}
}
2. 문자열을 입력받는 범용 메서드를 작성
- 코드
import java.util.Scanner;
public class Test02 {
public static String input() {
String str;
Scanner sc = new Scanner(System.in);
return str = sc.nextLine();
}
public static void main(String[] args) {
String name="";
System.out.print("이름을 입력하세요 : ");
name = input(); // 이름을 입력받을 때 input()메서드 실행
System.out.println(name+"님, 안녕하세요");
}
}
3. 특정 수를 입력받는 범용 메서드를 작성
- 코드
import java.util.Scanner;
public class Test03 {
public static int function(String str) {
Scanner sc = new Scanner(System.in);
System.out.println(str + " : ");
int tmp = sc.nextInt();
return tmp;
}
public static void main(String[] args) {
int num = function("국어"); // function()메서드에 매개변수로 '국어' 전달
System.out.println("국어 점수는 : "+num+"입니다");
}
}
'프로그래밍 > JAVA' 카테고리의 다른 글
객체 지향 프로그래밍 (0) | 2021.03.16 |
---|---|
자바 배열 (0) | 2019.04.25 |
자바 메서드 ( method ) (0) | 2019.04.21 |
자바 제어문 - 문제 (0) | 2019.04.19 |
제어문 - 2 ( for, while, do-while ) (0) | 2019.04.17 |