Question: Hello. I would like to add a delete function to case 3 that will delete a country from the countries.txt file, but I'm not sure
Hello. I would like to add a delete function to case 3 that will delete a country from the countries.txt file, but I'm not sure how to do it. As you can see in my code below, I have case 3, but nothing else.
My Code:
import java.io.FileReader; import java.io.FileWriter; import java.io.BufferedReader; import java.io.BufferedWriter; import java.util.ArrayList; import java.util.Scanner; import java.io.IOException; public class AC_CountryIO { ArrayList arrList = new ArrayList<>(200); int listSize = 0; int firstReadFlag = 0; public static void main(String[] args) throws IOException { AC_CountryIO obj = new AC_CountryIO(); Scanner inp = new Scanner(System.in); String ch; String coun = new String(); System.out.println(" Country List Manager "); System.out.println("COMMAND MENU: 1 - List Countries 2 - Add a Country 3 - Delete a Country 4 - Exit"); while(true) { System.out.print(" Enter menu number: "); ch = inp.next(); switch(ch) { case "1": obj.getCountries(); System.out.println("ListSize: " + obj.listSize); for(int i=0;i getCountries() throws IOException{ FileReader readFile = null; BufferedReader readBuff = null; try { readFile = new FileReader("countries.txt"); readBuff = new BufferedReader(readFile); if(firstReadFlag == 0) { String line = new String(); int i = 0; while((line = readBuff.readLine()) != null && i<195) { line = line.trim(); this.arrList.add(line); i++; } this.listSize = this.arrList.size(); readBuff.close(); readFile.close(); firstReadFlag = 1; } } catch(IOException iexcep) { FileWriter writeFile = null; BufferedWriter writeBuff = null; try { writeFile = new FileWriter("countries.txt"); writeBuff = new BufferedWriter(writeFile); } catch(IOException oexcep) { System.out.println(" Cannot create \"countries.txt\" file. Exiting..."); System.exit(0); } firstReadFlag = 1; writeBuff.close(); writeFile.close(); System.out.println(" No existing file named \"countries.txt\" was found. Created a new file named \"countries.txt\""); } return this.arrList; } public boolean saveCountries(ArrayList countries) throws IOException { FileWriter writeFile = null; BufferedWriter writeBuff = null; try { writeFile = new FileWriter("countries.txt"); writeBuff = new BufferedWriter(writeFile); } catch(IOException oexcep) { System.out.println(" Cannot find nor create \"countries.txt\" file. Exiting..."); System.exit(0); } String line = new String(); for(int i=0;i Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
