이 기사에서는 Java에서 두 숫자를 바꾸는 방법을 이해합니다. 이것은 임시 변수를 사용하여 수행됩니다.
아래는 동일한 데모입니다 -
입력
입력이 -
라고 가정합니다.value_1 : 45 value_2 : 70
출력
원하는 출력은 -
value_1 : 70 value_2 : 45
알고리즘
Step 1- Start Step 2- Declare three integers: value_1, value_2 and temp Step 3- Read the values Step 4- Assign value_1 to temporary variable Step 5- Assign value_2 to value_1 Step 6- Assign temporary variable to value_2 Step 6- Display the two values Step 7- Stop
예시 1
여기에서 입력은 프롬프트에 따라 사용자가 입력하고 있습니다. 우리코딩 그라운드 도구에서 이 예제를 라이브로 사용해 볼 수 있습니다. .
import java.util.Scanner; public class NumbersSwap{ public static void main(String[] args){ int value_1, value_2, my_temp; System.out.println("The required packages have been imported"); Scanner my_scan = new Scanner(System.in); System.out.println("A scanner object has been defined "); System.out.println("Enter the first number"); value_1 = my_scan.nextInt(); System.out.println("Enter the second number"); value_2 = my_scan.nextInt(); System.out.println("----Before swap----"); System.out.println("The first value is " + value_1 + " and the second value is " + value_2 ); my_temp = value_1; value_1 = value_2; value_2 = my_temp; System.out.println("----After swap----"); System.out.println("The first value is " + value_1 + " and the second value is " + value_2 ); } }
출력
The required packages have been imported A scanner object has been defined Enter the first number 112 Enter the second number 34 ----Before swap---- The first value is 112 and the second value is 34 ----After swap---- The first value is 34 and the second value is 112
예시 2
public class NumbersSwap{ public static void main(String[] args){ int value_1 , value_2, my_temp; System.out.println("The required packages have been imported"); value_1 = 45; value_2 = 70; System.out.println("----Before swap----"); System.out.println("The first number is " + value_1 + " and the second number is " + value_2 ); my_temp = value_1; value_1 = value_2; value_2 = my_temp; System.out.println("----After swap----"); System.out.println("The first number is " + value_1 + " and the second number is " + value_2 ); } }
출력
The required packages have been imported ----Before swap---- The first number is 45 and the second number is 70 ----After swap---- The first number is 70 and the second number is 45