JAVA

2일차 // 과제 (값의 교환 swap) 두개의 변수 데이터 값 교환하기

aesup 2021. 1. 12. 17:12
728x90

과제

두개의 정수 값을 입력 받고 x,y 변수에 저장한 후에 x,y 값을 바꾸고 출력하도록 프로그램을 작성하라.

int x, y;

 

x=1

y=2

 

출력

x=2  y=1

 

 

내가 푼 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
    public class Main{
    public static void main02(String[] args) {
        
        Scanner scan = new Scanner(System.in);
        int x, y;
        
        x = scan.nextInt();
        y = scan.nextInt();  
        
    
        System.out.print("x = " +  y);
        System.out.print(" ");
        System.out.print("y = " +  x);
    
    }
}
cs

강사님 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import java.util.Scanner;
 
public class Report01125 {
    
    public static void main(String[] args) {
        int x, y;
        x = 11;
        y = 22;
        
        int temp; //보관용 변수
        
        temp = x;
        x = y;
        y = temp;
        
        System.out.println("x = " +  x + "y = " + y);
    }
}
cs

 

저기서 temp 는 보관용 변수이다.

temp = x; // temp = 11, x = 11 

x = y; // x = 22 , y = 22;

y = temp; // y = 11

 

OUTPUT

 

x = 22, y = 11

 

728x90