I have a program where a user has to select an element of their choice from the linear search array. My program should display the question and the given array again when an user enters 1 to continue. I'm not sure where the while loop have to be and what code should be in the while loop, because if the user enters 1 to continue my program does not continue it just ends Here my code:
import java.util.Scanner;
public class SearchArray
{
public static int Search(int[] data, int key)
{
for (int i = 0; i < data.length; i++)
{
if (data[i] == key)
{
return i;
}//end of if statement
}//end of for loop
return -1;
}//end of search method
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int [] data= {74,56,45,14,78,100};
for(int element: data)
{
System.out.print(element + " , ");
}
System.out.println("Enter the key of your choice: ");
int key = in.nextInt();
int index = Search(data, key);
int option = 1;
System.out.println("Enter 1 to continue: ");
while(option ==1)
{
option=in.nextInt();
}
if(index!=-1)
{
System.out.println("Key: " + key + " Found at index: " + Search(data, key));
}//end of if statement
else
{
System.out.println("Key: " + key + " Is not found ");
}//end of else statement
}//end of main method
}//end of main class
create new class of itself. ie
if(sc.nextInt() == 1){
SearchArray sa = new SearchArray();
sa.main();
}
Try with this main method
public static void main(String... args) {
Scanner in = new Scanner(System.in);
int[] data = {74, 56, 45, 14, 78, 100};
for (int element : data) {
System.out.print(element + " , ");
}
while (true) {
System.out.println("Enter the key of your choice: ");
int key = in.nextInt();
int index = Search(data, key);
System.out.println("Key: " + key + " Found at index: " + index);
System.out.println("Enter 1 to continue: ");
while (in.nextInt() != 1) {
System.out.println("Enter 1 to continue: ");
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.