Westonci.ca connects you with experts who provide insightful answers to your questions. Join us today and start learning! Ask your questions and receive accurate answers from professionals with extensive experience in various fields on our platform. Discover detailed answers to your questions from a wide network of experts on our comprehensive Q&A platform.

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