Refactored Code for For:Each, not For.

This commit is contained in:
Aadit Agrawal 2024-08-10 10:45:42 +05:30
parent ee1a31b5e1
commit 9583d82a23

View File

@ -2,7 +2,7 @@ import java.util.Scanner;
public class ArraySearch { public class ArraySearch {
public static void main(String args[]){ public static void main(String args[]){
Scanner sc = new Scanner(System.in); Scanner sc = new Scanner(System.in);
int flag=0; int flag=0,index=0;
int[] array = {1,2,3,1,5,6,1,8,9}; int[] array = {1,2,3,1,5,6,1,8,9};
@ -10,12 +10,16 @@ public class ArraySearch {
int b = sc.nextInt(); int b = sc.nextInt();
System.out.println("The value is found at the locations: "); System.out.println("The value is found at the locations: ");
for(int i=0;i<9;i++){
if(array[i] == b){
System.out.print(" a["+i+"]"); for(int i:array){
if(i == b){
System.out.print(" a["+index+"]");
flag++; flag++;
} }
index++;
} }
if(flag==0){ if(flag==0){
System.out.print("None. The input value does not exist in the array."); System.out.print("None. The input value does not exist in the array.");
} }