Not sure where to post this question since its my first time on this forum. But I wanted to see if my code for swapping two variables is correct or if there is another way:
I did mines two ways:
First way (with known variables)
Input:
Second way(where the user has to input two variables)class RicMain { public static void main(String args[]) { int x = 10; int y = 20; System.out.println("Before swapping"); System.out.println("x = " + x); System.out.println("y = " + y); System.out.println("After swapping"); System.out.println("x = " + y); System.out.println("y = " + x); } }
import java.util.Scanner; class RicMain { public static void main(String args[]) { Scanner swap = new Scanner(System.in); int x, y; System.out.println("Enter num for x: "); x = swap.nextInt(); System.out.println("Enter num for y: "); y = swap.nextInt(); System.out.println("Before swap"); System.out.println("x = " + x); System.out.println("y = " + y); System.out.println("After swap"); System.out.println("x = " + y); System.out.println("y = " + x); } }
Are these good?