1

I have read several similar questions that have been posted on this forum, however mine is a slight variation. I do want to edit the first line, but the trick comes in where there can be a couple of lines that can have the same value. For instance, it is highly possible that in a class of hundred students at least two-three might have the same first name. Given this constraint, I decided to assign each student with a roll number which will be unique. So the final text file will look like this----

Leonhard

Euler

123

Carl

Guass

234

Leonhard

Galois

345

Now suppose the user wants to edit the first name of a student name Leonhard, then how should I o about programming it in such a way that only, say 345's first name gets edited?

Please help.......

Thank You.

Shrey Aryan
  • 41
  • 1
  • 6
  • 1
    please post your code – Panagiotis Giannakis Jan 11 '16 at 18:45
  • If the file format is not prescribed by your assignment, it may be simpler to either make one record per line, or reorder such that the ID is the first line in a record; that way if you need to operate on student #345, you just scan through the file for 345, and then you know the next line is the first name. – Gus Jan 11 '16 at 19:00

2 Answers2

0

I am not sure that I understand your requirement.

If you can read the whole file in a string, you can use the method replaceFirst of the String class:

String replaceFirst(String regex, String replacement)

Replaces the first substring of this string that matches the given regular expression with the given replacement.

because the first parameter is a regular expression, you can use it to find the record to update.

System.out.println("Giulio Cesare 000, Marco Aurelio 001, Marco Altieri 002, Pinco Pallino 003".replaceFirst("Marco (.*) 001", "Mario $1 001"));

In this example I used a comma separated string, but it shouldn't be so difficult to write a regular expression for a string with multiple lines.

For example, the following regex should work:

System.out.println("Giulio\r\nCesare\r\n000\r\nMarco\r\nAurelio\r\n001\r\nMarco\r\nAltieri\r\n002\r\nPinco\r\nPallino 003".replaceFirst("Marco\r\n(.*)\r\n001", "Mario\r\n$1\r\n001"));
Community
  • 1
  • 1
Marco Altieri
  • 3,726
  • 2
  • 33
  • 47
0

Now suppose the user wants to edit the first name of a student name Leonhard, then how should I o about programming it in such a way that only, say 345's first name gets edited?

Your data should be ordered in some form of record type. That way you can look up a record by ID (roll number in this case), and change only that record's data - even if multiple students have the same names (firstname, lastname).

For a more detailed example, see this.

Community
  • 1
  • 1
Danny_ds
  • 11,201
  • 1
  • 24
  • 46