Part 2: Write a second program in the same project that will perform the followi
ID: 3812783 • Letter: P
Question
Part 2:
Write a second program in the same project that will perform the following:
1. Ask the user for a last name they wish to search for.
2. Open the file you created for reading.
3. Read the student’s data from the file storing the data in variables.
4. If the last name matches the search name, display the record as shown in following example: John Smith SIU1234567 Peru Illinois 815-555-1212
5. Continue reading the file and displaying matches until the end is reached.
6. Ensure the code is well commented explaining what it does and how it works.
i need it in java
Explanation / Answer
LastNameSearch.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class LastNameSearch {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("D:\studentdata.txt");
Scanner fileData = new Scanner(file);
Scanner scan = new Scanner(System.in);
System.out.println("Enter ast name you wish to search for: ");
String lastName = scan.next();
boolean found = false;
while(fileData.hasNextLine()){//checking next line available
String record = fileData.nextLine(); //reading each line from file
String recordLastName = record.split("\s+")[0]; //getting last name from each line
if(lastName.equalsIgnoreCase(recordLastName)){ //checking matching with input or not
System.out.println("Record Found.");
System.out.println(record);
found = true;
}
}
if(!found) {
System.out.println("Record not found");
}
}
}
Output:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class LastNameSearch {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("D:\studentdata.txt");
Scanner fileData = new Scanner(file);
Scanner scan = new Scanner(System.in);
System.out.println("Enter ast name you wish to search for: ");
String lastName = scan.next();
boolean found = false;
while(fileData.hasNextLine()){//checking next line available
String record = fileData.nextLine(); //reading each line from file
String recordLastName = record.split("\s+")[0]; //getting last name from each line
if(lastName.equalsIgnoreCase(recordLastName)){ //checking matching with input or not
System.out.println("Record Found.");
System.out.println(record);
found = true;
}
}
if(!found) {
System.out.println("Record not found");
}
}
}
studentdata.txt
John Smith SIU1234567 Peru Illinois 815-555-1212
Murapaka Suresh SIU1234567 Peru Illinois 815-555-1211
Kella Revathhi SIU1234567 Peru Illinois 815-555-1213