Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.*;
- public class TestPerson{
- public static void main(String[] args)throws IOException{
- //check if file exists
- File myFile = new File(args[0]);
- try{
- if(!myFile.exists()){
- throw new FileNotFoundException();
- }
- }
- catch(FileNotFoundException fnfe){
- System.out.println("\nSorry, the file ["+args[0]+"] cannot be found.");
- System.exit(0);
- }
- //csv file reader
- BufferedReader in = new BufferedReader(new FileReader(myFile));
- //create person list
- List<Person> personList = new ArrayList<Person>();
- //add csv data to person list
- String str;
- while ((str = in.readLine()) != null){
- String[] data = str.split(",");
- personList.add(new Person(data[0],Integer.parseInt(data[1])));
- }
- printList(personList);
- //ask user what to edit
- Scanner scan = new Scanner(System.in);
- boolean invalidChoice;
- do{
- invalidChoice = false;
- try{
- System.out.print("\nWhich person would you like to edit? (Enter [-1] to exit): ");
- int choice = scan.nextInt();
- //exit if choice is -1
- if(choice == -1){
- System.exit(0);
- }
- editPerson(personList.get(choice));
- }
- catch(IndexOutOfBoundsException exc){
- System.out.println("\nRecord does not exist, please try again.");
- invalidChoice = true;
- }
- } while(invalidChoice);
- in.close();
- scan.close();
- //overwrite csv file
- PrintWriter personWriter = new PrintWriter(new FileWriter(args[0], false));
- for(Person p : personList){
- personWriter.println(p.getName()+","+p.getAge());
- }
- personWriter.close();
- printList(personList);
- }
- //method to edit
- public static Object editPerson(Person p){
- Scanner scan = new Scanner(System.in);
- System.out.print("Enter New Name for "+p.getName()+": ");
- String newName = scan.next();
- p.setName(newName);
- System.out.print("Enter New Age for "+p.getName()+": ");
- int newAge = scan.nextInt();
- p.setAge(newAge);
- return p;
- }
- //method to print
- public static void printList(List personList){
- ListIterator it = personList.listIterator();
- while(it.hasNext()){
- System.out.println("\nPerson " + it.nextIndex()+":");
- System.out.println(it.next());
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement