In: Computer Science
Write a Java program to move data among variables:
(1) define 4 int variable pos1, pos2, pos3, pos4, input 4 integer numbers from console and assign them to these variables; display message in the following format: “pos1=a-number; pos2=a-number; pos3=a-number; pos4=a-number”. “anumber” is replaced with real number.
(2) Left shift data in these variables: for each variable to get the value of the successive variable, with pos4 getting pos1's value. Display pos1, pos2, pos3, and pos4
(3) Right shift data in these variables: for each variable to get the value of the previous variable, with pos1 getting pos4's value. Display pos1, pos2, pos3, and
Java Program to move data among variables:
import java.util.Scanner; // importing Scanner class
class ShiftData {
public static void main(String args[]) {
//Defining 4 int variables
int pos1,pos2,pos3,pos4;
Scanner sc = new Scanner(System.in); //Using Scanner for getting input from console
//Prompting for input and storing value to variables
System.out.println("Enter value of pos1: ");
pos1 = sc.nextInt();
System.out.println("Enter value of pos2: ");
pos2 = sc.nextInt();
System.out.println("Enter value of pos3: ");
pos3 = sc.nextInt();
System.out.println("Enter value of pos4: ");
pos4 = sc.nextInt();
//Displaying value of all 4 variables
System.out.println("pos1="+pos1+";pos2="+pos2+";pos3="+pos3+";pos4="+pos4);
leftShift(pos1,pos2,pos3,pos4); //Calling leftShift method
rightShift(pos1,pos2,pos3,pos4); // Calling rightShift method
}
static void leftShift(int pos1,int pos2,int pos3,int pos4) {
int temp; //This variable is used to hold one pos value
//Shiftimg left (Getting value of successive variable)
temp = pos1;
pos1 = pos2;
pos2 = pos3;
pos3 = pos4;
pos4 = temp;
System.out.println("After left shift:");
System.out.println("pos1="+pos1+";pos2="+pos2+";pos3="+pos3+";pos4="+pos4); //Print variables after left shift
}
static void rightShift(int pos1,int pos2,int pos3,int pos4) {
int temp; //This variable is used to hold one pos value
//Shiftimg left (Getting value of previous variable)
temp = pos4;
pos4 = pos3;
pos3 = pos2;
pos2 = pos1;
pos1 = temp;
System.out.println("After right shift:");
System.out.println("pos1="+pos1+";pos2="+pos2+";pos3="+pos3+";pos4="+pos4); //Print variables after right shift
}
}
Sample Output :