I'm trying to work with arrays in Java, specifically in a method that delete the first appear of one element passed by param (or in this case make that the matched value convert to a 0), in this method I use a throwable exception if the matched value don't appear in the Array, but for any reason, this exception is always throwed.
Here is de code of the method:
public static void deleteElement(int[] array, int element) throws Exception {
for (int i = 0; i < array.length; i ) {
if (array[i] == element) {
array[i] = 0;
break;
} else if (array[i] != element) {
throw new Exception("Element not found");
}
}
}
When I call the method like this:
int[] array = new int[10];
try (Scanner sc = new Scanner(System.in)) {
for (int i = 0; i < array.length; i ) {
System.out.print("Introduce un numero: ");
array[i] = sc.nextInt();
}
}
try {
Arrayaba.deleteElement(array, 10);
} catch (Exception e) {
e.printStackTrace(); // The exception is always throwed
}
Showing the next error:
java.lang.Exception: Element not found
at LibreriaArraysBoludos.Arrayaba.deleteElement(Arrayaba.java:104)
at TestArrayaba.main(TestArrayaba.java:23)
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
at java.base/java.lang.reflect.Method.invoke(Method.java:578)
at jdk.compiler/com.sun.tools.javac.launcher.Main.execute(Main.java:434)
at jdk.compiler/com.sun.tools.javac.launcher.Main.run(Main.java:205)
at jdk.compiler/com.sun.tools.javac.launcher.Main.main(Main.java:132)
If any extra information is needed say it to me. Thanks in advance :)
CodePudding user response:
You have to throw the exception only when you have visited all the array, not at the first different element
public static void deleteElement(int[] array, int element) throws Exception {
for (int i = 0; i < array.length; i ) {
if (array[i] == element) {
array[i] = 0;
return;
}
}
throw new Exception("Element not found");
}
CodePudding user response:
You are saying that if this array[i] is not equal to the specified element in for, an exception will be thrown. First, i=0 , array[i]=element or not, if it is, it will be 0, and if it is not, an exception will be thrown. This is what your code says. In this case, this code only works when array[0]=element, and if not, an exception is thrown. What you are looking for is as follows:
public static void deleteElement(int[] array, int element) throws Exception {
for (int i = 0; i < array.length; i ) {
if (array[i] == element) {
array[i] = 0;
break;
}
}
throw new Exception("Element not found");
}