Algorithm training data exchange
Problem Description
Write a program, input two integers and store them in variables x and y respectively, and then use the function swap defined by yourself to exchange the values of these two variables.
Input format
The input is only one line, including two integers.
Output format
The output is only one line, and also two integers, that is, the result after the exchange.
Claim
The main function is responsible for the input and output of data, but it cannot directly exchange the values of these two variables. It must be done by calling the separately defined function swap. The swap function is only responsible for exchanging the values of the variables and cannot output the result of the exchange.
Sample input and output
Sample input
4 7
Sample output
7 4
Algorithm implementation
Since there is no pointer similar to C++ in Java, there are two methods I know of exchanging data, one is global variables, and the other is a custom reference data type. Use global variables to work around here.
import java.util.Scanner;
public class Main{
static int x,y;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
x = scanner.nextInt();
y = scanner.nextInt();
swap();
System.out.println(x+" "+y);
scanner.close();
}
private static void swap() {
int temp = x;
x = y;
y = temp;
}
}