public void removeDups() {
int i, k, j, lastFound = 0;
if (this.nElements < 1) {
System.out.println("Empty Array");
} else {
for (i = 0; i < this.nElements; i = lastFound) //outer loop
{
for (j = i + 1; j < this.nElements; j++) {
if (this.arr[i] == this.arr[j]) {
lastFound = i;
for (k = i; k < this.nElements; k++) {
this.arr[k] = this.arr[k + 1];
}
this.nElements--;
break;
}
}
}
for (i = 0; i < this.nElements; i++) {
System.out.println(this.arr[i]);
}
}
}
the previous method removes duplicates from the object invoking it (Array),the problem is that i want the outer loop to begin from a certain position every increment, i assign the value of that position to the variable lastFound and put that variable in the incremental part of the loop but the program goes to infinite loop and never stops, what is the problem with that?
You're setting i = lastFound at every iteration. At the start of the outer loop, initialize lastFound to i + 1. That way it will increment normally if you don't reset lastFound.
Alternatively, get rid of lastFound and when you find a match, set i = i - 1, start the k loop at i + 1 instead of i, and change the increment expression in the outer loop from i = lastFound to i++. I would also simplify your code by using System.arraycopy:
public void removeDups() {
if (nElements < 1) {
System.out.println("Empty Array");
} else {
for (int i = 0; i < nElements; i++) {
for (int j = i + 1; j < nElements; j++) {
if (arr[i] == arr[j]) {
System.arraycopy(arr, i + 1, arr, i, nElements - (i + 1));
nElements--;
i--;
break;
}
}
}
for (i = 0; i < nElements; i++) {
System.out.println(arr[i]);
}
}
}
Think of this: In first iteration,
i = 0
now if this is false: this.arr[i] == this.arr[j] then lastfound is never changed(remains 0), which will lead into infinite loop.
To fix the problem, handle the no match scenario.
Related
How do I avoid going below 0 with this for loop ? When this loop executes, it checks if both the vehicle and the garage are in the same space. If not, it decrements the vehicle loop by --i to get the next available vehicle. when it reaches to index 0, it is going below index -1 causing the program to crash.
for (int i = vehicles.size() - 1; i >= 0;) {
for (int j = 0; j < garage.size();) {
if (this.garage.get(j).getSpace() == this.vehicles.get(i).getSpace()) {
if (this.garage.get(j).garageRequest(vehicles.get(i).getvehiclesType())
&& this.garage.get(j).getLimit() > 0) {
this.garage.get(j).addvehicles(vehicles.get(i));
this.vehicles.remove(i);
i--;
break;
} else {
j++;
}
} else {
i--;
j = 0;
}
}
i tried the following at the end
else if(i != 0) {
i--;
j = 0;
}
Add a second condition to your inner loop. That is, change
for (int j = 0; j < garage.size();) {
to
for (int j = 0; j < garage.size() && i >= 0;) {
I am trying to search though the columns on a 2D array/matrix (of Boolean values) to find the column that is all false, then return the index of that column.
public int top() {
for (int j = 0; j < size; j++) {
for (int i = 0; i < size; i++) {
System.out.println("index i: "+ i+" index j:"+j);
if (matrix[i][j]==true) {
j++;
}
}
return j;
}
System.out.println("failed");
return -1;
}
I want to break out of the nested For loops when a "true" value is detected, and start the search again at the top of the next column. Right now, when a true value is detected, the column is incremented and it continues searching the next column where the last left off- not the beginning as I'd like.
Is there any way to detect something in a for loop, change the index, then restart the search?
You can use a while loop to only loop if matrix[i][j] is false. Then after checking a column, if it got to the end return the column index.
public int top() {
for (int j = 0; j < size; j++) {
int i = 0;
while(i < size && !matrix[i][j]){
System.out.println("index i: "+ i+" index j:"+j);
i++;
}
if(i == size){
return j;
}
}
System.out.println("failed");
return -1;
}
Yes, you can use continue and named loops for this purpose.
Notice how each loop is named with a self-explained name, making it easy to write the required algorithm
public int top() {
COLUMNS_LOOP:
for (int j = 0; j < size; j++) {
ROWS_LOOP:
for (int i = 0; i < size; i++) {
System.out.println("index i: " + i + " index j:" + j);
if (matrix[i][j]) {
continue COLUMNS_LOOP;
}
}
return j;
}
System.out.println("failed");
return -1;
}
public int top() {
for (int j = 0; j < size; j++) {
boolean failed = false;
for (int i = 0; i < size && !failed; i++) {
System.out.println("index i: "+ i+" index j:"+j);
if (matrix[i][j]) {
failed = true;
}
}
if (!failed) {
return j;
}
}
System.out.println("failed");
return -1;
}
We are setting "failed" to tru in case we got 1 "true" in a column.
Then, our inner for loop will stop to processed.
In case we didn't find "true" value, we will iterate all column, and then (because "failed" is false) we will return the first column that was all false
I tried to make method which inserts element at the specified position in this list.
Then Shifts the element & subsequent elements currently at that position to the
Right by adding one to their indices, i know there is shortcut for this method but I am suppose to do it, here what i tried to do but it's not working.
private T a[];
private int count;
private int size = 0;
public int size() { return size; }
public void add(int index,T t) throws Exception {
if (index < 0 || index > = a.length){
throw new IndexOutOfBoundsException();
}
Object[] temp = new Object[a.length + 1];
for (int k = 0, j = 0; j < temp.length; ++ k, ++ j){
if ( k == index ) {
temp[index] = t;
--k;
} else {
temp[j] = a[index]; //
}
}
a = (T[]) temp;
}
The trick to shifting is to start from the right, so:
for (int i = size; i > index; i--) {
a[i] = a[i - 1];
}
btw, when increasing size, normallyyou would double its size,rather than just growing by 1.
I corrected your 'for' block, try this:
for (int k = 0, j = 0; j < temp.length; ++k, ++j){
if ( k == index ) {
temp[index] = t;
--k;
index = -1;
} else {
temp[j] = a[k];
}
}
2 fixes i added:
index = -1; - In order to enter the if condition only 1 time, else it will constantly enter the condition
temp[j] = a[k]; - replaced to a[k], you was always taking value from a[index] means the same place, this is incorrect.
good luck :)
Is there a quicker way to increment a counter or break from an outer loop?
while(myArrayList.get(i) > myNumber) {
// some operations
if(i + 1 < myArrayList.size())
i++;
else
break;
}
A better way to write your code is definitely there:
for (int i = 0; i < myArrayList.size(); i++) {
if (myArrayList.get(i) <= myNumber) break;
//Some operations...
}
You need to check the size first to avoid running off the end of the list and getting an error.
int i;
for (i = 0; i < myArrayList.size(); i++)
if (myArrayList.get(i) <= myNumber)
break;
With the Streams API you could do
int n = IntStream.range(0, myArrayList.size())
.filter(i -> myArrayList.get(i) <= myNumber)
.findFirst()
.orElse(myArrayList.size()); // or -1
A for-loop is more appropriate here:
int counter = 0
for(int i = 0; i < myArrayList.size(); i++) {
if(!(myArrayList.get(i) > myNumber)) {
break;
}
counter++;
}
If the intention is count values that are greater than myNumber, then break will possibly exclude some values (unless you know that myArrayList is sorted), and the loop should rather be:
for(int i = 0; i < myArrayList.size(); i++) {
if(myArrayList.get(i) > myNumber) {
counter++;
}
}
I think you want to start counting from some index i,
int count=0;
for( ;((i < myArrayList.size()-1) && (myArrayList.get(i) > myNumber));i++){
count++;
}
I am trying to make the following number line is Java
2,3,5,7,11,13,17 (Prime Numbers)
I tried this code
for(int i =0; i <= 100; i++) {
if(i < 2) {
continue;
}
for(int j = 2; j < 1; j++) {
if(i % j == 0) {
break;
} else {
System.out.print(i + ",");
}
}
}
But it doesn't work
Anyone help please?
Your code is quite poor, but the minimal amount of changes needed to make it work yields this code:
outerLoop:
for(int i = 0; i <= 100; i++) {
if(i < 2) {
continue;
}
for(int j = 2; j < i; j++) {
if(i % j == 0) {
continue outerLoop;
}
}
System.out.print(i + ",");
}
But a further improvement would be to start the first loop at 2 right away:
outerLoop:
for(int i = 2; i <= 100; i++) {
for(int j = 2; j < i; j++) {
// and so on...
EDITED
There are a lot of errors in that code, first of all that second loop is a infinite loop and second one that the System.out.println line should not be in second loop it should be at end of first loop! If you place it in second it will print numbers hundreds of time.
This is the correct code :
for(int i = 2; i <= 100; i++)//begin loop from 2 instead of 0
{
boolean flag = true;
for(int j = 2; j < i; j++)
{
if(i % j == 0)
{
flag = false;
break;
}
}
if(flag)System.out.print(i + ",");
}
You need to set a flag to check if a factor was found outside the loop.