import java.io.*; public class findLast { public static void main(String[] args) { try { boolean matchFound = false; int[] x = {7, 8, 9, 10, 11, 12}; int y = 4; for (int i = x.length - 1; i >= 0 && matchFound == false; i--) { if (x[i] == y) { System.out.println("Index is " + i); matchFound = true; } else if (matchFound == false){ System.out.println(-1); } } } catch (NullPointerException e) { System.out.print("NullPointerException Caught"); } } }
C:\MS\src>java findLast
-1
-1
-1
-1
-1
-1
How to stop '-1' from getting printed again. ?Put in your loop (inside the if block)
break;
ndex is 2
-1
import java.io.*;
public class findLast {
public static void main(String[] args) {
try {
int[] x = {7, 8, 9, 10, 11, 12};
int y = 9;
for (int i = x.length - 1; i >= 0; i--) {
if (x[i] == y) {
System.out.println("Index is " + i);
break;
}
}
System.out.println(-1);
}
catch (NullPointerException e) {
System.out.print("NullPointerException Caught");
}
}
}
import java.io.*;
public class F {
public static void main(String[] args) {
try {
boolean matchFound = false;
int[] x = {7, 8, 9, 10, 11, 12};
int y = 10;
for (int i = x.length - 1; i >= 0 && matchFound == false; i--) {
if (x[i] == y) {
System.out.println("Index is " + i);
matchFound = true;
break;
}
}
if (matchFound == false){
System.out.println(-1);
}
}
catch (NullPointerException e) {
System.out.print("NullPointerException Caught");
}
}
}
You really could use just the following.
public class F {
public static void main(String[] args) {
boolean matchFound = false;
int[] x = {7, 8, 9, 10, 11, 12};
int y = 10;
for (int i = x.length - 1; i >= 0; i--) {
if (x[i] == y) {
System.out.println("Index is " + i);
matchFound = true;
break;
}
}
if (matchFound == false){
System.out.println(-1);
}
}
}
But what you ought to be doing is calling a method which returns an int - either the found value or -1.Quite right
public static int find(int n, int[] arr) {
int foundIndex = -1;
for (int i = arr.length - 1; i >= 0; i--) {
if (arr[i] == n) {
foundIndex = i;
break;
}
}
return foundIndex;
}
. . . prefer one exit point only
for(int i = 0; i < x.length; i++){
The last index is required
Why's that?because the class is called findLast
LastIndexFinder
because the class is called findLast
public static int find(int n, int[] arr) {
int foundIndex = -1;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == n) {
foundIndex = i;
}
}
return foundIndex;
}
import java.util.Arrays;
public class findLast {
public static void main(String[] args) {
// array to search
int[] arrint = {7, 8, 9, 10, 11, 12};
Integer[] arrInt = new Integer[arrint.length];
Arrays.setAll(arrInt, i -> arrint[i]);
// value to find
int val =10;
int idx = Arrays.asList(arrInt).indexOf(new Integer(val));
System.out.println(idx);
}
}
How about not using a loop?That does use a loop - just not visibly
Presumably the code is a learning exercise so shortcuts using the API are probably not wanted
Open in new window