How to iterate through an ArrayList of integer? [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have an ArrayList of Integer of {1, 3, 4, 5 , 6}
how do I iterate through the ArrayList so that i can print out the values in this manner in each loop?
1 and 3
1 and 4
1 and 5
1 and 6
3 and 4
3 and 5
3 and 6
4 and 5
4 and 6
5 and 6
I have tried doing a foreach loop, followed by a for loop and remove one object after the next but I encounter the ConcurrentModificationException. any help will be much appreciated!

I think this is what you want
- Iterate and remove first element
To avoid ConcurrentModificationException while iterating and removing element use standard old-fashioned for loops instead of foreach.
do
{
for (int j = 1; j < list.size(); j++)
{
System.out.println(list.get(0) + " and " + list.get(j));
}
list.remove(0);
}
while (list.size() != 0);

This code should work:
for (int i = 0; i < list.size() - 1; i++) {
for (int j = i + 1; j < list.size(); j++) {
System.out.println(list.get(i) + " and " + list.get(j));
}
}

Related

for loop is skipping to the end? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I am fairly new to Java, but my for loop is instantly skipping to the highest possible value in the following code:
System.out.println(i);
for(i = 0; i <= (difficulty - 2); i++);{
System.out.println(i);
nextMineX = (int) (10*Math.random());
nextMineY = (int) (10*Math.random());
for(y = 0; y <= 14; y++){
System.out.println(y);
if(nextMineX == minesX[y] && nextMineY == minesY[y]){
i = i-1;
} else{
minesX[i] = nextMineX;
minesY[i] = nextMineY;
}
}
}
The first for loop is screwing up, while the nested one is running fine. the variable i is initialized as 0, and difficulty is at 16. the output of this excerpt is as follows:
0
14
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
If anyone can help me with his that would be extremely appreciated. Since I'm new, it is probably something small and basic that I'm overlooking.
The problem is the semicolon at the end of the second line. It's valid to have a for loop with no body. It's also valid to have standalone a block of code inside brackets (this defines a scope for variables--if you defined a variable inside the brackets, it wouldn't be available outside). So Java is interpreting the beginning of your code like this:
for(i = 0; i <= (difficulty - 2); i++); // for loop is done, so i = difficulty - 2
{
System.out.println(i);
...
Your for loop statement ends with the semicolon you have
for(i = 0; i <= (difficulty - 2); i++); <- incorrect
for(i = 0; i <= (difficulty - 2); i++){ <- correct
//body
}
For loop is terminating cause of semicolon ;
for(i = 0; i <= (difficulty - 2); i++); //semicolon terminating loop
{...}
so you should use for loop like this
for(i = 0; i <= (difficulty - 2); i++) //remove semicolon prevent to terminate
{...}

Insertion sort array java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
So I have to write code for an insertion sort that will sort an array of random ints, the array is already set up and working okay and everything but my sort is not, heres what i have:
for(int i =1; i< numberSort.length-1;i++){
int temp = numberSort[i];
int j = i-1;
while((j >= 0) && (numberSort[j]>temp)){
numberSort[j+1] = numberSort[j];
j = j-1;
}
numberSort[j+1] = temp;
}
}
It seems to me that that should work, however it does not, it moves the numbers around from their original position but does not order them in ascending order. Thanks for any help you may be able to offer.
This code works for me:
public static void main(String[] args) {
int[] numberSort = {22,7,2, 5, 7, 1, 2, 9,33,55,12,1,0};
for (int i = 1; i < numberSort.length; i++) {
int temp = numberSort[i];
int j = i - 1;
while ((j >= 0) && (numberSort[j] > temp)) {
numberSort[j + 1] = numberSort[j];
j = j - 1;
}
numberSort[j + 1] = temp;
}
for (int i = 0; i < numberSort.length; i++) {
System.out.println(numberSort[i]);
}
}
Gives output:
0
1
1
2
2
5
7
7
9
12
22
33
55

Adding Elements in an array [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 4;
items_arr = 4;
System.out.println("The elements in the array are: ");
for (int x = 0; x < items_arr; x++)
System.out.println("Array[" + x + "]=" + array[x]);
System.out.print("\n");
Scanner insert = new Scanner(System.in);
System.out.print("Enter an Element to Insert: ");
int input = insert.nextInt();
for (s = 0; s < items_arr; s++)
if (array[s] == input)
break;
items_arr++;
for (s = 0; s < items_arr; s++)
System.out.println("Array[" + s + "]=" + array[s]);
break;
The output is. The elements are
Array [0]= 1
Array [1]= 2
Array [2]= 3
Array [3]= 4
Enter an element to Insert: 5
Array [0]= 1
Array [1]= 2
Array [2]= 3
Array [3]= 4
Array [4]= 0
when I insert 5 it posts 0
any suggestions please.. thanks!
To insert in to the array you shuould be doing follwoing operation
array[s]=input
Two notes here
Arrays are fixed length, and you should be checking the array length before inserting values in to that,other wise you will get ArrayIndexOBException. Safer to sue List/Set
As better coding practise, and to improve the readablity, you should be enclosing the conditional/loop statements (such as if or for) - see eg below
eg: 1
for (int x = 0;x<items_arr;x++) {
System.out.println("Array["+x+"]="+array[x]);
}
eg 2:
for(int s = 0; s < items_arr; s++) {
if (array[s] == input) {
break;
}
}
You have not inserted 5 in your array,
do something after items_arr++
array[ items_arr] = input;
If you do not insert any thing then by default every element is 0
You should be using a Collection type; I would recommend an ArrayList - that is -
List<Integer> al = new ArrayList<Integer>();
for (int i = 1; i < 5; i++) {
al.add(i);
}
Scanner insert = new Scanner(System.in);
System.out.print("Enter an Element to Insert: ");
int input = insert.nextInt();
al.add(input); // And so on...
You are not updating/inserting the array with the new input.
for(s = 0; s < items_arr; s++)
if (array[s] == input)
break;
items_arr++;
just replace the above code with
array[ items_arr] = input;
items_arr++;

Increment all integer elements by 1 in a ArrayList [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I need to increment the values for certain part of a ArrayList by a given number.
like [ 1 2 3 4 5 6 7 8 9 1 1 1 ]
lets say i need to increment last 3 elements by 2
so that the result would be
[ 1 2 3 4 5 6 7 8 9 3 3 3 ]
how can i do this ?
Assuming arrayList contains the ArrayList<Integer> instance:
int startFrom = arrayList.size() - 3;
int upTo = arrayList.size();
int incrBy = 2;
for (int i = startFrom; i < upTo && i < arrayList.size(); i += 1) {
int oldValue = arrayList.get(i);
int newValue = oldValue + incrBy;
arrayList.set(i, newValue);
}
or, more compactly (i.e. inlining the variables oldValue and newValue):
for (int i = startFrom; i < upTo && i < arrayList.size(); i += 1) {
arrayList.set(i, arrayList.get(i) + incrBy);
}
Assuming that the part that needed to be incremented in known [from, to] . You just loop on the ArrayList and add the number you wish: (remember that you can access the items in the ArrayList by index)
arr - is ArrayList
number - is the number you wish to increment by
for (int i = from; i < to; i++){
int item = arr.get(i);
arr.set(i,item+number);
}
I assume here that from and to are valid indexes for the ArrayList but you should always check if they are within the array bounds
Hint : ArrayList provides indexed access to its members. You can easily loop over the required elements. For incrementing last n elements make use of a for loop and list's size().

The value of the loop counter of a for loop is one larger than I expect after exit from the loop [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a simple for loop, which lets the loop counter, i go up to 5.
int i;
double n = 1 / 2;
for (i = 2; i <= 5; i++) {
n = n + 1.0 / i;
}
System.out.print(i);
So I expect the value of the counter to be 5 after the loop finishes. But the value is 6, nit 5. Why is that?
Thanks
Because you are incrementing i value as i++ in for{..} loop
for (i = 2; i <= 5; i++)
^ here
In for loop after checking the condition, body part will be executed
after that increment or decrement will be done
Process will be
<----
1step 2step 4step
for (i = 2; i <= 5; i++){
/*body part*/
3step
}
After 4th step it will moves to check 2nd step i.e. condition part
So thats why it prints the i value as
6
The for loop:
for (i = 2; i <= 5; i++) {
// code
}
which has condition i <= 5 and the condition will be false when i = 6 and the loop breaks, goes to the print line.
Thanks for reminding me my first time programming experience, When I used to write a code a = 5 and printed it to see what it shows in the console. :)
The i++ is the same as saying i = i + 1. In this case you can also use ++i and get the same result.

Categories

Resources