Respuesta :
Answer:
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.IOException;
public class LabProgram {
public static String findID(String studentName, Scanner infoScnr) throws Exception {
while (infoScnr.hasNextLine()) {
String[] parts = infoScnr.nextLine().split(" ");
if (parts[0].trim().equals(studentName)) {
return parts[1].trim();
}
}
throw new Exception("Student ID not found for " + studentName);
}
public static String findName(String studentID, Scanner infoScnr) throws Exception {
while (infoScnr.hasNextLine()) {
String[] parts = infoScnr.nextLine().split(" ");
if (parts[1].trim().equals(studentID)) {
return parts[0].trim();
}
}
throw new Exception("Student ID not found for " + studentID);
}
public static void main(String[] args) throws IOException {
Scanner scnr = new Scanner(System.in);
String studentName;
String studentID;
String studentInfoFileName;
FileInputStream studentInfoStream = null;
Scanner studentInfoScanner = null;
// Read the text file name from user
studentInfoFileName = scnr.next();
// Open the text file
studentInfoStream = new FileInputStream(studentInfoFileName);
studentInfoScanner = new Scanner(studentInfoStream);
// Read search option from user. 0: findID(), 1: findName()
int userChoice = scnr.nextInt();
try {
if (userChoice == 0) {
studentName = scnr.next();
studentID = findID(studentName, studentInfoScanner);
System.out.println(studentID);
} else {
studentID = scnr.next();
studentName = findName(studentID, studentInfoScanner);
System.out.println(studentName);
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
scnr.close();
studentInfoStream.close();
}
}
Explanation:
- You should call your file the same as your class (i.e., LabProgram.java)
- I added a try/catch to both find calls, to catch the exception
- The find methods are very similar, they loop through the lines of the roster, splitting each line at a space and doing string comparison.