Solved

# Shifting Array Element Left

Posted on 2011-03-09
Medium Priority
468 Views
Hello All

I am trying to shift an element to the left.  I want 5050 to become 0550.

Here's my code.  I don't know what I'm doing wrong.

``````class TestArrays {
public static void main(String[] args) {
int[] ia = new int[101];
for (int i = 0; i < ia.length; i++)
ia[i] = i;
int sum = 0;
for (int i = 0; i < ia.length; i++)
sum += ia[i];
System.out.println(sum);

sum = 0;
System.arraycopy(ia, 1, ia, 0, ia.length-1);
for (int i = 0; i < ia.length; i++)
sum += ia[i];

System.out.println(sum);

}
}
``````

Can anyone show me how to shift an element left?

Thanks

RichW
0
Question by:RichW
• 3

LVL 47

Expert Comment

ID: 35089757
Sorry how would 5050 become 0550 by shifting?
do you mean 5050 ---> 0505 ?
0

LVL 4

Author Comment

ID: 35089769
If you shift the first 0 to the left, it would be 0550, no?
0

LVL 47

Accepted Solution

for_yan earned 2000 total points
ID: 35089791
OK, so you have an array - your task is to move element at posiion j (j>0) to position j-1, and you don't care
what happens with the previous value of element j-1 - and what happens with the new element j either - correct?

Then why woould not you jsut simply say a[j-1] = a[j];

0

LVL 47

Expert Comment

ID: 35089808
Or you want to exchange elements at position j and j-1 - that would be another task, but also simple:

int temp = a[j-1];
a[j-1]=a[j];
a[j] = temp;

0

LVL 36

Expert Comment

ID: 35089830
So what is your requirement for shifting then? To find the first zero and shift it one place to the left? Why the zero and why only the first zero?
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
###### Suggested Courses
Course of the Month6 days, 16 hours left to enroll