0% found this document useful (0 votes)
20 views

Array Searching

Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Array Searching

Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

words yes hellopackage javaprogram.

ArraySearching;
import java.util.Scanner;

public class ArraySearching {

public static void main(String[] args) {


// Define the array to store the names
String[] names = new String[100];
int count = 0; // keep track of the number of names in the array

// Create a Scanner object to get user input


Scanner input = new Scanner(System.in);

while (true) {
// Display the menu
System.out.println("|||||||||||||||||||||||||||||||||||||");
System.out.println("|| 1. Add a name ||");
System.out.println("|| 2. Search for a name ||");
System.out.println("|| 3. View all names ||");
System.out.println("|| 4. Quit ||");
System.out.println("|||||||||||||||||||||||||||||||||||||");
System.out.print("|| Enter your choice (1-4): ");

// Get the user's choice


int choice = input.nextInt();

// Process the user's choice


switch (choice) {
case 1:
// Add a name to the array

System.out.println("|||||||||||||||||||||||||||||||||||||");
System.out.print("|| Enter a name: ");
String name = input.next();
names[count] = name;
count++;
System.out.println("|| Name added successfully!
||");
break;

case 2:
// Search for a name in the array
System.out.print("|| Enter a name to search for: ");
name = input.next();
boolean found = false;
for (int i = 0; i < count; i++) {
if (names[i].equals(name)) {

System.out.println("|||||||||||||||||||||||||||||||||||||");
System.out.println("|| "+name + " is in the
list! ||");
found = true;
break;
}
}
if (!found) {
System.out.println("|| "+name + " is not in the
list. ||");
}
break;

case 3:
// Display all the names in the array

System.out.println("|||||||||||||||||||||||||||||||||||||");
System.out.println("|| Current names in the list:
||");
for (int i = 0; i < count; i++) {
System.out.println("|| "+names[i]);

System.out.println("|||||||||||||||||||||||||||||||||||||");
break;

case 4:
// Exit the program

System.out.println("|||||||||||||||||||||||||||||||||||||");
System.out.println("|| Goodbye!
||");

System.out.println("|||||||||||||||||||||||||||||||||||||");
System.exit(0);
break;

default:
// Invalid choice

System.out.println("|||||||||||||||||||||||||||||||||||||");
System.out.println("|| Invalid choice. Try again.
||");
}
}
}
}

You might also like