In this code, if the variable "search" is not in the array then I'm getting "Not found" i times. What to do for printing it once if the variable search is not in the array?
import java.util.*;
public class Main {
public static void main(String args[]) {
try (Scanner sc = new Scanner(System.in)) {
int i;
System.out.print("Enter size of the array: ");
int size = sc.nextInt();
int[] arrayInput = new int[size];
for (i = 0; i < size; i ) {
System.out.printf("Enter %d array value: ", i);
arrayInput[i] = sc.nextInt();
}
System.out.print("Enter the number you want to search in array: ");
int search = sc.nextInt();
for (i = 0; i < arrayInput.length; i ) {
if (arrayInput[i] == search) {
System.out.println("Number found at the index " i);
break;
}else{
System.out.println("Not found");
}
}
}
;
}
}
CodePudding user response:
Try to move the println
outside the for loop adding a return in case of number found.
import java.util.*;
public class Main {
public static void main(String args[]) {
try (Scanner sc = new Scanner(System.in)) {
int i;
System.out.print("Enter size of the array: ");
int size = sc.nextInt();
int[] arrayInput = new int[size];
for (i = 0; i < size; i ) {
System.out.printf("Enter %d array value: ", i);
arrayInput[i] = sc.nextInt();
}
System.out.print("Enter the number you want to search in array: ");
int search = sc.nextInt();
for (i = 0; i < arrayInput.length; i ) {
if (arrayInput[i] == search) {
System.out.println("Number found at the index " i);
return;
}
}
System.out.println("Not found");
}
;
}
}
CodePudding user response:
You could also store the index of the integer and the print it after exiting the loop.
import java.util.*;
public class Main {
public static void main(String args[]) {
try (Scanner sc = new Scanner(System.in)) {
int i, index = -1;
System.out.print("Enter size of the array: ");
int size = sc.nextInt();
int[] arrayInput = new int[size];
for (i = 0; i < size; i ) {
System.out.printf("Enter %d array value: ", i);
arrayInput[i] = sc.nextInt();
}
System.out.print("Enter the number you want to search in array: ");
int search = sc.nextInt();
for (i = 0; i < arrayInput.length; i ) {
if (arrayInput[i] == search) {
index = i;
break;
}
}
if(index < 0){
System.out.println("Not found");
}
else{
System.out.println("Number found at the index " index);
}
}
}
}