I'm trying to figure out how to search for a specific student by first name and then change their specific data and finally write it back out to the same file keeping all other data unchanged. I'm not sure how to start the methods or what the correct algorithms would be for achieving this. The code so far looks like this:
import java.util.Scanner; import java.io.PrintWriter; import java.io.FileNotFoundException; import java.io.File; public class MainClass { public static void main (String [] args) { final int MAX_SIZE = 20; Student [ ] myClass = new Student [MAX_SIZE]; Scanner inFile = null; try { inFile = new Scanner (new File ("inData.txt")); } catch (FileNotFoundException ex) { System.out.println ("file not found"); System.exit(0); } int size = 0; while (inFile.hasNext ()) { String aLine = inFile.nextLine (); aLine = aLine.trim (); int pos = aLine.indexOf(" "); String fName = aLine.substring(0,pos); aLine = aLine.substring(pos); aLine = aLine.trim (); pos = aLine.indexOf(" "); String lName = aLine.substring (0,pos); aLine = aLine.substring(pos); aLine = aLine.trim (); pos = aLine.indexOf(" "); String phone = aLine.substring (0,pos); aLine = aLine.substring(pos); aLine = aLine.trim (); double gpa = Double.parseDouble(aLine); myClass[size] = new Student (fName,lName,phone,gpa); size++; if (size == MAX_SIZE) break; } System.out.println ("data read from file....."); for (int i = 0; i < size; i++) System.out.print(myClass[i]); System.exit (0); } public static void findName(String name){ } }
public class Student { private String firstName; private String lastName; private String phone; private double GPA; public Student ( ) { firstName = ""; lastName = ""; phone = ""; GPA = 0; } public Student (String fN, String lN, String pH, double gpa) { firstName = fN; lastName = lN; phone = pH; GPA = gpa; } public String toString () { return "\n\nfirst name: " + firstName + "\nlast name: " + lastName + "\nphone: " + phone + "\nGPA: " + GPA; } }