Explore Westonci.ca, the premier Q&A site that helps you find precise answers to your questions, no matter the topic. Explore comprehensive solutions to your questions from a wide range of professionals on our user-friendly platform. Explore comprehensive solutions to your questions from knowledgeable professionals across various fields on our platform.
Sagot :
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.
Your visit means a lot to us. Don't hesitate to return for more reliable answers to any questions you may have. Thanks for using our service. We're always here to provide accurate and up-to-date answers to all your queries. Keep exploring Westonci.ca for more insightful answers to your questions. We're here to help.