Need help with shifting all values to the left of an array and place a 0 in the last location each time it is called.?
Create a new Java program called LeftShift.
Create an array size 10 that contains 1’s and 0’s only. (Any combination.)
Create a method called shiftValues that passes an array. It should shift all values to the left and place a 0 in the last location each time it is called.
Call your shiftValues method a three times to show shift.
Paste code here once completed.
NOTE: To earn the extra credit, program must show use of the pass by reference concept, which means you should only have one array throughout the entire program.
import java.util.*;
public class LeftShift{
static Random r=new Random();
public static final int dice=2;
public static final int size=10;
public static final int count=5;
public static void main(String[] args){
int[] a=new int[size];
for(int i=0;i<size;i++){
int seq=r.nextInt(dice);
a[i]=seq;
}
System.out.println("Sequence: "+Arrays.toString(a));
for(int i=0;i<count;i++){
shiftValues(a);
}
}
public static void shiftValues(int[] a){
for(int i=0;i<a.length-1;i++){
a[i]=a[i+1];
a[a.length-1]=0;
}
System.out.println("Sequence: "+Arrays.toString(a));
}
}
Answers
brilliant_moves
Hi, kupokupo. Your code is nearly right, but I've had to make some changes.
import java.util.*;
public class LeftShift{
... static Random r=new Random();
... public static final int dice=2;
... public static final int size=10;
... public static final int count=3;
... public static void main(String[] args){
... ... int[] a=new int[size];
... ... for(int i=0;i<size;i++){
... ... ... int seq=r.nextInt(dice);
... ... ... a[i]=seq;
... ... }
... ... System.out.println("Sequence: "+Arrays.toString(a));
... ... for(int i=0;i<count;i++){
... ... ... System.out.println ("Sequence: "+Arrays.toString (shiftValues(a)));
... ... }
... }
... public static int[] shiftValues(int[] a){
... ... for(int i=0;i<a.length-1;i++){
... ... ... a[i]=a[i+1];
... ... }
... ... a[a.length-1]=0;
... ... return a;
... }
}
//Note: To show indentation (which Y!A removes), I've used "... ". Replace dots with a tab or spaces in your code.
Was this article helpful?
Thank you! Your feedback will help us improve the support experience.
Related questions
Describe a system that must send 32 bits of data on a serial bus (limited to 8 bits at a time).?
You should describe the frame schema you will use, what error detection it will use, and how the devices will signal the start and end of each part of the message. Be sure to inclu...
Which programming languages would you recommend I learn if I want a Computer Science related job in 2019?
Languages I've practiced with the most: Java, C++, C. Java is by far my favorite programming language.
Languages I feel like I'm not very used to using: SQL, Swift, Assembly, Matl...