Welcome to Westonci.ca, your go-to destination for finding answers to all your questions. Join our expert community today! Explore our Q&A platform to find reliable answers from a wide range of experts in different fields. Our platform provides a seamless experience for finding reliable answers from a network of experienced professionals.

A common programming operation is to swap or exchange the values of two variables. If the value of x is currently 19 and the value of y is 42, swapping them will make x into 42 and y into 19. Write a program named Swap.java that allows the user to enter two int values. The program should store those values into variables and then swap the variables. Print the values of both variables before and after the swap. You will receive full credit as long as your solution works, but try to do this using as few variables as possible

Sagot :

Answer:

import java.util.Scanner;

public class Swap

{

public static void main(String[] args) {

   

    Scanner input = new Scanner(System.in);

    int x, y, t;

 System.out.print("Enter the first variable: ");

 x = input.nextInt();

 System.out.print("Enter the second variable: ");

 y = input.nextInt();

 

 System.out.printf("Values before the swap -> x = %d, y = %d\n", x, y);

 

 t = x;

 x = y;

 y = t;

 

 System.out.printf("Values after the swap -> x = %d, y = %d\n", x, y);

}

}

Explanation:

Import the Scanner class

Create a Scanner object to be able to get input from the user

Declare the variables, x, y, and t - the variable t will be used as temporary variable that will hold the value of x

Ask the user to enter the first and second variables

Print the values before swap

Assign the value of x to the t

Assign the value of y to the x (Now, x will have the value of y)

Assign the value of the t to the y (Since t holds the value of x, y will have the value of x)

Print the values after the swap